<?php

require_once XOOPS_ROOT_PATH.'/modules/legacy/admin/class/ModuleInstallUtils.class.php';

class Xdbmigrate_InstallUtils extends Legacy_ModuleInstallUtils{
    /**
     * installSQLAutomatically
     *
     * @param   XoopsModule  &$module
     * @param   Legacy_ModuleInstallLog  &$log
     *
     * @return  bool
    **/
    public function installSQLAutomatically(/*** XoopsModule ***/ &$module,/*** Legacy_ModuleInstallLog ***/ &$log)
    {

        $sqlFileInfo =& $module->getInfo('sqlfile');
        if(!isset($sqlFileInfo[XOOPS_DB_TYPE]))
        {
            return true;
        }
        $sqlFile = $sqlFileInfo[XOOPS_DB_TYPE];

        $dirname = $module->getVar('dirname');
        $sqlFilePath = sprintf('%s/%s/%s',XOOPS_MODULE_PATH,$dirname,$sqlFile);
        if(!file_exists($sqlFilePath))
        {
            $sqlFilePath = sprintf(
                '%s/modules/%s/%s',
                XOOPS_TRUST_PATH,
                $module->modinfo['trust_dirname'],
                $sqlFile
            );
        }
        
        require_once XOOPS_MODULE_PATH . '/legacy/admin/class/Legacy_SQLScanner.class.php';    // TODO will be use other class?
        $scanner = new Legacy_SQLScanner();
        $scanner->setDB_PREFIX(XOOPS_DB_PREFIX);
        $scanner->setDirname($dirname);
        if(!$scanner->loadFile($sqlFilePath))
        {
            $log->addError(
                XCube_Utils::formatString(
                    _MI_USER_INSTALL_ERROR_SQL_FILE_NOT_FOUND,
                    $sqlFile
                )
            );
            return false;
        }

        $scanner->parse();
        $root =& XCube_Root::getSingleton();
        $db =& $root->mController->getDB();

        foreach($scanner->getSQL() as $sql)
        {
            if(!$db->query($sql))
            {
                $log->addError($db->error());
                return false;
            }
        }
        $log->addReport(_MI_XDBMIGRATE_INSTALL_MSG_DB_SETUP_FINISHED);
        return true;
    }

    public function installDataAutomatically(/*** XoopsModule ***/ &$module,/*** Legacy_ModuleInstallLog ***/ &$log) {
        $dirname = $module->getVar('dirname');
		$trustDirname = $module->modinfo['trust_dirname'];
        $sql = "insert into ".XOOPS_DB_PREFIX."_xdbmigrate_status ".
                "(app_id,status) ".
                'VALUES(0,0)';
        $db = &Database::getInstance();
        if($db->queryF($sql) === FALSE){
          return false;
        }
        return true;
    }
}
