<?php

if (!defined('XOOPS_ROOT_PATH')) exit();

require_once XOONIPS_TRUST_PATH . '/admin/class/installer/XoonipsInstallUtils.class.php';

/**
 * Xoonips_Uninstaller
**/
class Xoonips_Uninstaller
{
    /**
     * @brief   Legacy_ModuleInstallLog
    **/
    public $mLog = null;

    /**
     * @brief   bool
    **/
    private $_mForceMode = false;

    /**
     * @brief   XoopsModule
    **/
    private $_mXoopsModule = null;

    /**
     * __construct
     * 
     * @param   void
     * 
     * @return  void
    **/
    public function __construct()
    {
        $this->mLog = new Legacy_ModuleInstallLog();
    }

    /**
     * setCurrentXoopsModule
     * 
     * @param   XoopsModule  &$xoopsModule
     * 
     * @return  void
    **/
    public function setCurrentXoopsModule(/*** XoopsModule ***/ &$xoopsModule)
    {
        $this->_mXoopsModule =& $xoopsModule;
    }

    /**
     * setForceMode
     * 
     * @param   bool  $isForceMode
     * 
     * @return  void
    **/
    public function setForceMode(/*** bool ***/ $isForceMode)
    {
        $this->_mForceMode = $isForceMode;
    }

    /**
     * _uninstallModule
     * 
     * @param   void
     * 
     * @return  void
    **/
    private function _uninstallModule()
    {
        $moduleHandler =& xoops_gethandler('module');
    
        if($moduleHandler->delete($this->_mXoopsModule))
        {
            $this->mLog->addReport(_MI_XOONIPS_INSTALL_MSG_MODULE_INFORMATION_DELETED);
        }
        else
        {
            $this->mLog->addError(_MI_XOONIPS_INSTALL_ERROR_MODULE_INFORMATION_DELETED);
        }
    }

    /**
     * _uninstallTables
     * 
     * @param   void
     * 
     * @return  void
    **/
    private function _uninstallTables()
    {
        $root =& XCube_Root::getSingleton();
        $db =& $root->mController->getDB();
        $dirname = $this->_mXoopsModule->get('dirname');
    
        $tables =& $this->_mXoopsModule->getInfo('tables');
        if(is_array($tables))
        {
            foreach($tables as $table)
            {
            	/*
                $tableName = str_replace(
                    array('{prefix}','{dirname}'),
                    array(XOOPS_DB_PREFIX,$dirname),
                    $table
                );
                */
                $tableName = $db->prefix($table);
                $sql = sprintf('drop table `%s`;',$tableName);
                
                if($db->query($sql))
                {
                    $this->mLog->addReport(
                        XCube_Utils::formatString(
                            _MI_XOONIPS_INSTALL_MSG_TABLE_DOROPPED,
                            $tableName
                        )
                    );
                }
                else
                {
                    $this->mLog->addError(
                        XCube_Utils::formatString(
                            _MI_XOONIPS_INSTALL_ERROR_TABLE_DOROPPED,
                            $tableName
                        )
                    );
                }
            }
        }
        
       // extend tables
       for ($i=0; $i<100; $i++) {
        	$exist = false;
        	$tableName = XOOPS_DB_PREFIX.'_'.$dirname.'_item_extend'.$i;
        	$sql = "SHOW TABLES LIKE '%${tableName}'";
        	$result = $db->query($sql);
        	while ($row = $db->fetchArray($result)) {
        		$exist = true;
        	}
        	if ($exist) {
        		$sql = sprintf('drop table `%s`;',$tableName);
        		if($db->query($sql))
        		{
        			$this->mLog->addReport(
        					XCube_Utils::formatString(
        							_MI_XOONIPS_INSTALL_MSG_TABLE_DOROPPED,
        							$tableName
        					)
        			);
        		}
        	}
    	}
    }

    /**
     * _uninstallTemplates
     * 
     * @param   void
     * 
     * @return  void
    **/
    private function _uninstallTemplates()
    {
        Xoonips_InstallUtils::uninstallAllOfModuleTemplates($this->_mXoopsModule,$this->mLog,false);
    }

    /**
     * _uninstallBlocks
     * 
     * @param   void
     * 
     * @return  void
    **/
    private function _uninstallBlocks()
    {
        Xoonips_InstallUtils::uninstallAllOfBlocks($this->_mXoopsModule,$this->mLog);
    
        $tplHandler =& xoops_gethandler('tplfile');
        $cri = new Criteria('tpl_module',$this->_mXoopsModule->get('dirname'));
        if(!$tplHandler->deleteAll($cri))
        {
            $this->mLog->addError(
                XCube_Utils::formatString(
                    _MI_XOONIPS_INSTALL_ERROR_BLOCK_TPL_DELETED,
                    $tplHandler->db->error()
                )
            );
        }
    }

    /**
     * _uninstallPreferences
     * 
     * @param   void
     * 
     * @return  void
    **/
    private function _uninstallPreferences()
    {
        Xoonips_InstallUtils::uninstallAllOfConfigs($this->_mXoopsModule,$this->mLog);
    	Xoonips_InstallUtils::deleteAllOfNotifications($this->_mXoopsModule, $this->mLog);
		Xoonips_InstallUtils::deleteAllOfComments($this->_mXoopsModule, $this->mLog);
    }

    /**
     * _processReport
     * 
     * @param   void
     * 
     * @return  void
    **/
    private function _processReport()
    {
        if(!$this->mLog->hasError())
        {
            $this->mLog->add(
                XCube_Utils::formatString(
                    _MI_XOONIPS_INSTALL_MSG_MODULE_UNINSTALLED,
                    $this->_mXoopsModule->get('name')
                )
            );
        }
        else if(is_object($this->_mXoopsModule))
        {
            $this->mLog->addError(
                XCube_Utils::formatString(
                    _MI_XOONIPS_INSTALL_ERROR_MODULE_UNINSTALLED,
                    $this->_mXoopsModule->get('name')
                )
            );
        }
        else
        {
            $this->mLog->addError(
                XCube_Utils::formatString(
                    _MI_XOONIPS_INSTALL_ERROR_MODULE_UNINSTALLED,
                    'something'
                )
            );
        }
    }

    /**
     * executeUninstall
     * 
     * @param   void
     * 
     * @return  bool
    **/
    public function executeUninstall()
    {
        $this->_uninstallTables();
        if(!$this->_mForceMode && $this->mLog->hasError())
        {
            $this->_processReport();
            return false;
        }
    
        if($this->_mXoopsModule->get('mid') != null)
        {
            $this->_uninstallModule();
            if(!$this->_mForceMode && $this->mLog->hasError())
            {
                $this->_processReport();
                return false;
            }
    
            $this->_uninstallTemplates();
            if(!$this->_mForceMode && $this->mLog->hasError())
            {
                $this->_processReport();
                return false;
            }
    
            $this->_uninstallBlocks();
            if(!$this->_mForceMode && $this->mLog->hasError())
            {
                $this->_processReport();
                return false;
            }
    
            $this->_uninstallPreferences();
            if(!$this->_mForceMode && $this->mLog->hasError())
            {
                $this->_processReport();
                return false;
            }
            
        	$this->_processScript();
			if (!$this->_mForceMode && $this->mLog->hasError()) {				
				$this->_processReport();
				return false;
			}
        }
        $this->_processReport();
        return true;
    }
    
	function _processScript() {				
		if (!$this->moduleUninstall( $this->_mXoopsModule)) {
			$this->mLog->addError(XCube_Utils::formatMessage(_AD_LEGACY_ERROR_FAILED_TO_EXECUTE_CALLBACK, 'moduleUninstall'));
		}		
	}

	function moduleUninstall($xoopsMod) {
		$mydirname = $xoopsMod->getVar('dirname');
	
		$uid = $GLOBALS['xoopsUser']->getVar('uid', 'n');
		$mid = $xoopsMod->getVar('mid', 'n');
	
		// show original 'user' and 'login' blocks
		$sys_blocks = array('user' => array(), 'login' => array());
		if (defined('XOOPS_CUBE_LEGACY')) {
		    // for XOOPS Cube Legacy 2.2
		    $sys_blocks['user'][] = array('legacy', 'b_legacy_usermenu_show');
		    $sys_blocks['login'][] = array('user', 'b_user_login_show');
		}
		$sys_blocks['user'][] = array('system', 'b_system_user_show');
		$sys_blocks['login'][] = array('system', 'b_system_login_show');
		foreach ($sys_blocks as $type => $sys_type_blocks) {
			foreach ($sys_type_blocks as $sys_block) {
	    		list($dirname, $show_func) = $sys_block;
				$sysmid = Xoonips_InstallUtils::getModuleId($dirname);
	    		if ($sysmid === false) {
					continue; // module not found
				}
				$bids = Xoonips_InstallUtils::getBlockIds($sysmid, $show_func);
				foreach ($bids as $bid) {
					Xoonips_InstallUtils::setBlockPosition($bid, true, 0, 0);
				}
				if (count($bids) != 0) {
					break; // found this type's block
				}
			}
		}
		return true;
	}
}


