<?  // vim:set et ts=4 sw=4 sts=4:
# Copyright (C) 2003-2013 Axentra Corporation.
#
# This is UNPUBLISHED PROPRIETARY SOURCE CODE OF Axentra Corporation.
# The copyright notice above does not evidence any actual or intended
# publication of such source code. The contents of this file may not
# be disclosed to third parties, copied or duplicated in any form, in
# whole or in part, without the prior written permission of
# Axentra Corporation.
#
namespace HipPlayConnect;


use DB;


// little hack in case it's not defined (CLI scripts)
if ( !defined( 'DB_TYPE' ) )
    define( 'DB_TYPE', 'sqlite3' );

// singleton Object that creates unique/single instances of db connections
class AxDB
{
	private  $_databases = array();

    /**
     * Singleton instance
     * @var AxDB
     */
	private static $_dbObj = null;

	private function connect($dbname)
	{
	    $databasePath = ( $dbname == 'registration' ? '/var/lib/sqlite/' : '/home/0db/' ) . $dbname;
	    
        // make sure the database file exists (if sqlite3)
        if ( DB_TYPE == 'sqlite3' && ( !file_exists( $databasePath ) || 0 == filesize( $databasePath ) ) )
        {
            error_log( "ERROR - opening $databasePath DB: file does not exist or is empty" );
            return false;
        }
        else
        {
            /** @var object $res */
            /** @noinspection PhpUnusedLocalVariableInspection */
            $res = $this->_databases[ $dbname ] = DB::connect( DB_TYPE . ':///' . $databasePath  . '?mode=0664' );
    		
    		if( DB::isError($res ) )			
    		{
    			error_log("ERROR - opening $dbname DB: " . $res->getMessage());
    			return false;
    		}	
		
    		$res->setFetchMode( DB_FETCHMODE_ASSOC );
        }
		
		return true;
	}

    /**
     * @param $dbname
     *
     * @return \DB_sqlite3
     */
	static public function getInstance($dbname)
	{	
		if( is_null( AxDB::$_dbObj ) )
		{
			AxDB::$_dbObj = new AxDB();			
		}
		
		if (
			!array_key_exists( $dbname, AxDB::$_dbObj->_databases ) &&
			!AxDB::$_dbObj->connect($dbname)
		) 
		{
			error_log("Error connecting to DB");
			return null;
		}
			
		return AxDB::$_dbObj->_databases[ $dbname ];
	}

    /**
     * Returns the SQLite condition to use to match $fsPath and its descendants
     *
     * @param object $dbConn the database connection
     * @param string $fsPath path to match
     * @param string $pathColumn
     *
     * @return string the SQLite condition
     */
	static public function getArborescenceCondition( $dbConn, $fsPath, $pathColumn = 'fsPath' ) {
	    return
	        'substr( ' . $pathColumn . ' || ' . $dbConn->quoteSmart( '/' ) . ', 1, length( ' . $dbConn->quoteSmart( $fsPath . '/' ) . ' ) ) = ' .
	        $dbConn->quoteSmart( $fsPath . '/' );
	}

    /**
     * Returns the SQLite condition to use to the descendants of $fsPath
     *
     * @param object $dbConn the database connection
     * @param string $fsPath path to match
     * @param string $pathColumn
     *
     * @return string the SQLite condition
     */
    static public function getDescendantsCondition( $dbConn, $fsPath, $pathColumn = 'fsPath' ) {
        return
            'substr( ' . $pathColumn . ', 1, length( ' . $dbConn->quoteSmart( $fsPath . '/' ) . ' ) ) = ' .
            $dbConn->quoteSmart( $fsPath . '/' );
    }

	/**
	 * Returns the SQLite condition to use to match only the direct descendants of $fsPath
	 *
	 * @param object $dbConn the database connection
	 * @param string $fsPath path to match
	 * @return string the SQLite condition
	 */
	static public function getDirectDescendantsCondition( $dbConn, $fsPath ) {
	    return
	        'substr( fsPath, 1, length( ' . $dbConn->quoteSmart( $fsPath . '/' ) . ' ) ) = ' .
	        $dbConn->quoteSmart( $fsPath . '/' ) . ' AND ' .
	        'substr( fsPath, length( ' . $dbConn->quoteSmart( $fsPath . '/' ) . ' ) + 1, length( fsPath ) - length( ' . $dbConn->quoteSmart( $fsPath . '/' ) . ' ) ) ' .
	        'NOT LIKE "%/%"';
	}

    /**
     * @param object $dbConn
     * @param string $oldFile
     * @param string $newFile
     *
     * @return string
     */
	static public function getChangedPath( $dbConn, $oldFile, $newFile ) {
	    return
	    	$dbConn->quoteSmart( $newFile ) . ' || ' .
	    	'substr( ' .
	    		'fsPath, ' .
	    		'length( ' . $dbConn->quoteSmart( $oldFile ) . ' ) + 1, ' .
	    	    'length( fsPath ) - length( ' . $dbConn->quoteSmart( $oldFile ) . ' ) ' .
	    	')';
	}

}
