<?php
/**
 * @version $Id: Module.class.php 679 2012-08-20 12:41:35Z hodaka $
 * @package myuploader
 */

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

require_once dirname(dirname(__FILE__))."/class/AbstractAction.class.php";
require_once dirname(dirname(__FILE__))."/class/Global.class.php";

define('MYUPLOADER_FRAME_PERFORM_SUCCESS', 1);
define('MYUPLOADER_FRAME_PERFORM_FAIL', 2);
define('MYUPLOADER_FRAME_INIT_SUCCESS', 3);

define('MYUPLOADER_FRAME_VIEW_NONE', 'none');
define('MYUPLOADER_FRAME_VIEW_SUCCESS', 'success');
define('MYUPLOADER_FRAME_VIEW_ERROR', 'error');
define('MYUPLOADER_FRAME_VIEW_INDEX', 'index');
define('MYUPLOADER_FRAME_VIEW_INPUT', 'input');
define('MYUPLOADER_FRAME_VIEW_PREVIEW', 'preview');
define('MYUPLOADER_FRAME_VIEW_CANCEL', 'cancel');

/**
 * Myuploader_Module
**/
class Myuploader_Module extends Legacy_ModuleAdapter
{
    /**
     * @var  string
     *
     * @public
    **/
    var $mActionName = null;

    /**
     * @var  Myuploader_AbstractAction
     *
     * @public
    **/
    var $mAction = null;

    /**
     * @var  bool
     *
     * @public
    **/
    var $mAdminFlag = false;

    /**
     * @var  Myuploader_AssetManager
     *
     * @public
    **/
    var $mAssetManager = null;

    /**
     * startup
     *
     * @param   void
     *
     * @return  void
     *
     * @public
    **/
    function startup()
    {
        parent::startup();

        XCube_DelegateUtils::call(
            'Module.myuploader.Event.GetAssetManager',
            new XCube_Ref($this->mAssetManager),
            $this->mXoopsModule->get('dirname')
        );

        $root = XCube_Root::getSingleton();
        $root->mController->mExecute->add(array(&$this, 'execute'));

        //
        // TODO/Insert your initialization code.
        //
    }

    /**
     * setAdminMode
     *
     * @param   bool  $flag
     *
     * @return  void
     *
     * @public
    **/
    function setAdminMode($flag)
    {
        $this->mAdminFlag = $flag;
    }

    /**
     * _getDefaultActionName
     *
     * @param   void
     *
     * @return  string
     *
     * @private
    **/
    function _getDefaultActionName()
    {
        // TODO insert your default action name
        $op = xoops_getrequest('op');
        if ($op == null) {
            if($this->mAdminFlag)
                $op = 'CategoryList';
            else
                $op = 'ImageList';
        }

        return $op;
    }

    /**
     * setActionName
     *
     * @param   string  $name
     *
     * @return  void
     *
     * @public
    **/
    function setActionName($name)
    {
        $this->mActionName = $name;
    }

    /**
     * getRenderSystemName
     *
     * @param   void
     *
     * @return  string
     *
     * @public
    **/
    function getRenderSystemName()
    {
        if(!$this->mAdminFlag)
        {
            return parent::getRenderSystemName();
        }

        // TODO will be use site config
        if(!defined('MYUPLOADER_ADMIN_RENDER_REGISTED'))
        {
            define('MYUPLOADER_ADMIN_RENDER_REGISTED', true);
            $root = XCube_Root::getSingleton();
            $root->overrideSiteConfig(
                array(
                    'RenderSystems' => array(
                        'Myuploader_AdminRenderSystem' => 'Myuploader_AdminRenderSystem'
                    ),
                    'Myuploader_AdminRenderSystem' => array(
                        'root' => XOOPS_TRUST_PATH.'/modules/'.$this->mAssetManager->mTrustDirname,
                        'path' => '/admin/class/MyuploaderAdminRenderSystem.class.php',
                        'class' => 'Myuploader_AdminRenderSystem'
                    )
                )
            );
        }

        return 'Myuploader_AdminRenderSystem';
    }

    /**
     * getAdminMenu
     *
     * @param   void
     *
     * @return  {string 'title',string 'link',string 'keywords',bool 'show',bool 'absolute'}[]
     *
     * @public
    **/
    function getAdminMenu()
    {
        if(is_array($this->mAdminMenu))
        {
            return $this->mAdminMenu;
        }

        $root = XCube_Root::getSingleton();

        // load admin menu
        $adminMenu = $this->mXoopsModule->getInfo('adminmenu');
        if(!is_array($adminMenu))
        {
            $adminMenu = array();
        }

        // add preference menu
        if(is_array($this->mXoopsModule->getInfo('config')) && count($this->mXoopsModule->getInfo('config')) > 0)
        {
            $adminMenu[] = array(
                'title'    => _PREFERENCES,
                'link'     => $root->mController->getPreferenceEditUrl($this->mXoopsModule),
                'absolute' => true
            );
        }

        // add help menu
        if($this->mXoopsModule->hasHelp())
        {
            $adminMenu[] = array(
                'title'    => _HELP,
                'link'     => $root->mController->getHelpViewUrl($this->mXoopsModule),
                'absolute' => true
            );
        }

        $this->mAdminMenu = array();
        foreach($adminMenu as $menu)
        {
            if(!(isset($menu['absolute']) && $menu['absolute']))
            {
                $menu['link'] = XOOPS_MODULE_URL . '/' . $this->mXoopsModule->get('dirname') . '/' . $menu['link'];
            }
            $this->mAdminMenu[] = $menu;
        }

        return $this->mAdminMenu;
    }

    /**
     * execute
     *
     * @param   XCube_Controller  &$controller
     *
     * @return  void
     *
     * @private
    **/
    function execute(&$controller)
    {
        $this->_createAction();

        $this->_checkPermission();

        $viewStatus = (Myuploader_Utils::getEnv('REQUEST_METHOD') == 'POST') ?
            $this->mAction->execute() :
            $this->mAction->getDefaultView();

        // assign module header
        Myuploader_Utils::assignModuleHeader($this->mAssetManager->mDirname);

        switch($viewStatus)
        {
            case MYUPLOADER_FRAME_VIEW_SUCCESS:
                $this->mAction->executeViewSuccess($this->getRenderTarget());
                break;
            case MYUPLOADER_FRAME_VIEW_ERROR:
                $this->mAction->executeViewError($this->getRenderTarget());
                break;
            case MYUPLOADER_FRAME_VIEW_INDEX:
                $this->mAction->executeViewIndex($this->getRenderTarget());
                break;
            case MYUPLOADER_FRAME_VIEW_INPUT:
                $this->mAction->executeViewInput($this->getRenderTarget());
                break;
            case MYUPLOADER_FRAME_VIEW_PREVIEW:
                $this->mAction->executeViewPreview($this->getRenderTarget());
                break;
            case MYUPLOADER_FRAME_VIEW_CANCEL:
                $this->mAction->executeViewCancel($this->getRenderTarget());
                break;
            default:
                break;
        }
    }

    /**
     * _createAction
     *
     * @param   void
     *
     * @return  void
     *
     * @private
    **/
    function _createAction()
    {
        $root = XCube_Root::getSingleton();

        if($this->mActionName == null)
        {
            $this->mActionName = $root->mContext->mRequest->getRequest('op');
            if($this->mActionName == null)
            {
                $this->mActionName = $this->_getDefaultActionName();
            }
        }

        if(!ctype_alnum($this->mActionName))
        {
            $this->doActionNotFoundError();
            die();
        }

        $fileName = ($this->mAdminFlag ? '/admin' : '')
            . '/actions/' . ucfirst($this->mActionName) . 'Action.class.php';
        switch(true)
        {
            case file_exists(
                $path = XOOPS_MODULE_PATH.'/'.$this->mXoopsModule->get('dirname').$fileName
            ):
                break;
            case file_exists(
                $path = XOOPS_TRUST_PATH.'/modules/'.$this->mAssetManager->mTrustDirname.$fileName
            ):
                break;
            default:
                $this->doActionNotFoundError();
                die();
        }

        require_once $path;

        $className = 'Myuploader_' . ($this->mAdminFlag ? 'Admin_' : '')
            . ucfirst($this->mActionName) . 'Action';
        if(class_exists($className))
        {
            $this->mAction = new $className();
        }

        if(!is_object($this->mAction))
        {
            $this->doActionNotFoundError();
            die();
        }

        if($this->mAction->prepare() === false)
        {
            $this->doPreparationError();
            die();
        }
    }

    /**
     * _checkPermission
     *
     * @param   void
     *
     * @return  void
     *
     * @private
    **/
    function _checkPermission()
    {
        $root = XCUbe_Root::getSingleton();
        $user =& $root->mContext->getUser();
        if(
            (!$this->mAction->hasPermission()) ||
            ($this->mAction->isMemberOnly() && !$user->isInRole('Site.RegisteredUser')) ||
            ($this->mAction->isAdminOnly() && !$user->isInRole('Module.' . $this->mXoopsModule->get('dirname') . '.Admin'))
        )
        {
            $this->doPermissionError();
            die();
        }
    }

    /**
     * doActionNotFoundError
     *
     * @param   void
     *
     * @return  void
     *
     * @private
    **/
    function doActionNotFoundError()
    {
        XCube_DelegateUtils::call(
            'Module.' . $this->mXoopsModule->get('dirname') . '.Event.Exception.ActionNotFound'
        );
        $root = XCube_Root::getSingleton();
        $root->mController->executeForward(XOOPS_URL);
    }

    /**
     * doPreparationError
     *
     * @param   void
     *
     * @return  void
     *
     * @private
    **/
    function doPreparationError()
    {
        XCube_DelegateUtils::call(
            'Module.' . $this->mXoopsModule->get('dirname') . '.Event.Exception.Preparation'
        );
        $root = XCube_Root::getSingleton();
        $root->mController->executeForward(XOOPS_URL);
    }

    /**
     * doPermissionError
     *
     * @param   void
     *
     * @return  void
     *
     * @private
    **/
    function doPermissionError()
    {
        XCube_DelegateUtils::call(
            'Module.' . $this->mXoopsModule->get('dirname') . '.Event.Exception.Permission'
        );
        $root = XCube_Root::getSingleton();
        $root->mController->executeForward(XOOPS_URL);
    }
}

?>