<?php

namespace Hura8\Components\Template\Controller;

use Liquid\Cache\File;
use Liquid\Liquid;
use Liquid\Template as LiquidTemplate;

class TemplateController
{

    const TEMPLATE_DIR              = ROOT_DIR ."/template/web/";
    const TEMPLATE_ASSETS_DIR       = PUBLIC_DIR."/static/assets/";
    const TEMPLATE_TMP_UPLOAD_DIR   = ROOT_DIR . "/template/_uploaded/";

    protected $template_set         = '';
    protected $web_template_path    = ''; // hold html tmp
    protected $assets_template_path = ''; // hold tpl assets like css/js/images
    protected $assets_public_path = ''; // to view in url

    public static $setting_template_path = ROOT_DIR . '/template/setting'; // (ie. email, sms, etc...)

    protected static $cache_dir = ROOT_DIR . "/var/cache/public_template/";


    public function __construct($template_set='default')
    {
        $this->template_set             = $template_set;
        $this->web_template_path        = self::TEMPLATE_DIR . $template_set;
        $this->assets_template_path     = self::TEMPLATE_ASSETS_DIR . $template_set;
        $this->assets_public_path       = join('/', ['', 'static', 'assets', $template_set]) ;
    }


    /**
     * @param string $language_prefix
     * @param string $layout
     * @param $routing array
     * @return string
     */
    public static function getPublicTemplateFile($language_prefix="", $layout="pc", array $routing=[]): string{
        $tpl_file = str_replace('-', '_', $routing['view']). '.html';
        if($layout != 'pc') $tpl_file = $layout.'_'.$tpl_file;

        if($language_prefix) $tpl_file = $language_prefix."_".$tpl_file;

        return join( DIRECTORY_SEPARATOR, [
            $routing['module'],
            $tpl_file
        ]);
    }


    /**
     * @param string $language_prefix
     * @param string $layout
     * @return string
     */
    public static function getSiteThemeFile($language_prefix="", $layout = 'pc'): string
    {
        $tpl_file = "index.html";
        if($layout != 'pc') $tpl_file = $layout.'_'.$tpl_file;

        if($language_prefix) return $language_prefix."_".$tpl_file;

        return $tpl_file;
    }


    public static function flushCache() {
        try {

            $cache = new File([
                'cache_dir' => self::$cache_dir
            ]);

            $cache->flush();

        }catch (\Exception $exception) {

        }
    }

    /*
     * 2 ways to render a html template
     * 1. Use $html_to_parse, which requires no dependencies
     *  Example:
     *  Template::parse(null, 'Age =  {{age}}', ['age' => 21], '');
     *
     * 2. Use $template_file_path, which requires dependency $path
     *  Template::parse(Template::$setting_template_path, null, ['age' => 21], 'email/test');
     *
     * */
    public static function parse($path = null, $html_to_parse = null, array $data = [], $template_file_path = '') {

        if(!$html_to_parse && !$template_file_path) {
            return 'Nothing to parse';
        }

        //output to html
        Liquid::set('INCLUDE_SUFFIX', 'html');
        Liquid::set('INCLUDE_PREFIX', '');
        //Liquid::set('INCLUDE_ALLOW_EXT', true);
        Liquid::set('ESCAPE_BY_DEFAULT', false);

        $enable_cache = false; // default = true, turn this on-off to disable cache while working on local mode
        //$enable_cache = true;

        //catch exception and print friendly notice
        try {

            $objLiquidTemplate = new LiquidTemplate( $path );
            $objLiquidTemplate->registerFilter( TemplateFilter::class );
            if($enable_cache) {
                $objLiquidTemplate->setCache(new File([
                    'cache_dir' => self::$cache_dir
                ]));
            }

            if($html_to_parse) {
                $objLiquidTemplate->parse($html_to_parse);
            }elseif ($template_file_path) {
                $objLiquidTemplate->parseFile($template_file_path);
            }

            return $objLiquidTemplate->render($data);

        } catch (\Exception $e) {
            $result = [];
            do {
                //printf("%s:%d %s (%d) [%s]\n", $e->getFile(), $e->getLine(), $e->getMessage(), $e->getCode(), get_class($e));
                //echo $e->getTraceAsString();
                //$code = $e->getTrace()[0]['args'][0];
                //if(is_array($code)) $code = serialize($code);
                $result[] = sprintf(
                    "
Lỗi code trong file template html: <br />
- Chi tiết lỗi: %s<br />
- File template: %s<br />
- Cache Dir: %s<br />
- Hướng dẫn xử lý: Tách từng phần html để kiểm tra và nhấn F5 mỗi lần. Nếu không xuất hiện thông báo này nghĩa là phần đó không tạo lỗi
",
                    $e->getMessage(),
                    substr($template_file_path, strrpos($template_file_path, DIRECTORY_SEPARATOR) + 1 ),
                    static::$cache_dir
                );

            } while($e = $e->getPrevious());

            return join(" - ", $result);
        }
    }


    public function getWebTemplatePath() {
        return $this->web_template_path;
    }

    public function getWebPublicAssetsUrl() {
        return $this->assets_public_path;
    }

    public function getWebTemplateAssetsPath() {
        return $this->assets_template_path;
    }

}
