<?php

class Module extends ModuleCore
{
    /*
    ** Template management (display, overload, cache)
    */
    protected static function _isTemplateOverloadedStatic($module_name, $template)
    {
        require_once(dirname(__FILE__).'../../../../modules/designer/defines.inc.php');
        if (Tools::file_exists_cache(getThemeDir().'modules/'.$module_name.'/'.$template))
            return true;
        elseif (Tools::file_exists_cache(_PS_MODULE_DIR_.$module_name.'/views/templates/hook/'.$template))
            return false;
        elseif (Tools::file_exists_cache(_PS_MODULE_DIR_.$module_name.'/'.$template))
            return false;
        return null;
    }

    public function display($file, $template, $cacheId = null, $compileId = null)
    {
        require_once(dirname(__FILE__).'../../../../modules/designer/defines.inc.php');
        if (($overloaded = Module::_isTemplateOverloadedStatic(basename($file, '.php'), $template)) === null)
            $result = Tools::displayError('No template found for module').' '.basename($file, '.php');
        else
        {
            $this->smarty->assign(array(
                'module_dir' =>				__PS_BASE_URI__.'modules/'.basename($file, '.php').'/',
                'module_template_dir' =>	($overloaded ? getThemeUrl() : __PS_BASE_URI__).'modules/'.basename($file, '.php').'/',
                'module_name' => $this->name
            ));

            $smarty_subtemplate = $this->context->smarty->createTemplate(
                $this->getTemplatePath($template),
                $cacheId,
                $compileId,
                $this->smarty
            );

            $result = $smarty_subtemplate->fetch();
        }
        return $result;
    }

    /**
     * Get realpath of a template of current module (check if template is overriden too)
     *
     * @@since 1.5.0
     * @@param string $template
     * @@return string
     */
    public function getTemplatePath($template)
    {
        require_once(dirname(__FILE__).'../../../../modules/designer/defines.inc.php');
        $overloaded = $this->_isTemplateOverloaded($template);
        if ($overloaded === null)
            return null;
        if ($overloaded)
            return getThemeDir().'modules/'.$this->name.'/'.$template;
        else if (file_exists(_PS_MODULE_DIR_.$this->name.'/views/templates/hook/'.$template))
            return _PS_MODULE_DIR_.$this->name.'/views/templates/hook/'.$template;
        else
            return _PS_MODULE_DIR_.$this->name.'/'.$template;
    }

    protected function _getApplicableTemplateDir($template)
    {
        require_once(dirname(__FILE__).'../../../../modules/designer/defines.inc.php');
        return $this->_isTemplateOverloaded($template) ? getThemeDir() : _PS_MODULE_DIR_.$this->name.'/';
    }
}
