<?php
class Design extends Buyers
{
    private $smarty;
    private $frontend_compile_dir;

    public function __construct()
    {
        // Создаем и настраиваем Смарти
        require_once 'modules/smarty/Smarty.class.php';

        // Создаем и настраиваем Смарти
        $this->smarty = new Smarty();
        $this->smarty->compile_check = $this->config->smarty_compile_check;
        $this->smarty->caching = $this->config->smarty_caching;
        $this->smarty->cache_lifetime = $this->config->smarty_cache_lifetime;
        $this->smarty->debugging = $this->config->smarty_debugging;
        $this->smarty->error_reporting = E_ERROR | E_PARSE;

        $this->smarty->cache_dir = $this->config->root_dir . 'cache';
        $this->smarty->compile_dir = $this->frontend_compile_dir = $this->smarty->cache_dir . '/theme';
        $this->smarty->template_dir = $this->config->root_dir . 'design/' . $this->settings->theme . '/html';

        // Создаем папку для скомпилированных шаблонов текущей темы
        if(!file_exists($this->smarty->compile_dir))
            mkdir($this->smarty->compile_dir, 0755, true);

        $this->smarty->registerPlugin('modifier', 'resize',    array($this, 'resize_modifier'));
        $this->smarty->registerPlugin('modifier', 'plural',    array($this, 'plural_modifier'));
        $this->smarty->registerPlugin('modifier', 'first',     array($this, 'first_modifier'));
        $this->smarty->registerPlugin('modifier', 'cut',       array($this, 'cut_modifier'));
        $this->smarty->registerPlugin('modifier', 'date',      array($this, 'date_modifier'));
        $this->smarty->registerPlugin('modifier', 'time',      array($this, 'time_modifier'));
        $this->smarty->registerPlugin('modifier', 'tel',       array($this, 'tel_modifier'));
        $this->smarty->registerPlugin('modifier', 'size',      array($this, 'size_modifier'));
        $this->smarty->registerPlugin('modifier', 'filemtime', array($this, 'filemtime_modifier'));
        $this->smarty->registerPlugin('modifier', 'path',      array($this, 'path_modifier'));

        $this->smarty->registerPlugin('function', 'url',       array($this, 'url_plugin'));
        $this->smarty->registerPlugin("function", 'packer',    array($this, "packer_plugin"));
        $this->smarty->registerPlugin('function', 'api',       array($this, 'api_plugin'));
    }

    public function assign($var, $value = false)
    {
        if(is_array($var))
            return $this->smarty->assign($var);

        return $this->smarty->assign($var, $value);
    }

    //передадим в шаблон то что там может пригодиться
    public function fetch($template)
    {
        $this->assign('routes',     $this->routes);
        $this->assign('config',     $this->config);
        $this->assign('settings',   $this->settings);

        if($this->smarty->caching)
            $content = $this->smarty->fetch($template, md5($_SERVER['REQUEST_URI']));
        else
            $content = $this->smarty->fetch($template);

        return $content;
    }

    public function set_templates_dir($dir)
    {
        $this->smarty->template_dir = $dir;
    }

    public function set_compiled_dir($dir)
    {
        $this->smarty->compile_dir = $dir;
    }

    public function get_compile_dir()
    {
        return $this->frontend_compile_dir;
    }

    public function get_var($name)
    {
        return $this->smarty->getTemplateVars($name);
    }

    public function resize_modifier($filename, $width = 0, $height = 0, $option = "auto", $blob = false)
    {
        return $this->images->create_resize($filename, $width, $height, $option, $blob);
    }

    public function filemtime_modifier($file)
    {
        return filemtime($file);
    }

    public function url_plugin($params)
    {
        if(is_array(reset($params)))
            return $this->request->url(reset($params));
        else
            return $this->request->url($params);
    }

    public function plural_modifier($number, $singular, $plural1=null, $plural2=null)
    {
        if(empty($plural1))
            list($singular, $plural1, $plural2) = explode(":", $singular);

        $number = abs($number);
        if(!empty($plural2))
        {
            $p1 = $number%10;
            $p2 = $number%100;
            if($number == 0)
                return $number.' '.$plural1;
            if($p1==1 && !($p2>=11 && $p2<=19))
                return $number.' '.$singular;
            elseif($p1>=2 && $p1<=4 && !($p2>=11 && $p2<=19))
                return $number.' '.$plural2;
            else
                return $number.' '.$plural1;
        }
        else
        {
            if($number == 1)
                return $number.' '.$singular;
            else
                return $number.' '.$plural1;
        }
    }

    public function tel_modifier($phone)
    {
        return preg_replace("/[^0-9\+]/", "", $phone);
    }

    public function path_modifier($page)
    {
        return $this->pages->get_path($page->id);
    }

    public function first_modifier($params = array())
    {
        if(!is_array($params))
            return false;
        return reset($params);
    }

    public function cut_modifier($array, $frst=1, $sec=false)
    {
        if(!$sec)
            $sec = count($array);

        return array_slice($array, $frst, $sec, true);
    }

    public function date_modifier($date, $format = null)
    {
        $default_format = "d F Y";

        if(empty($date))
            $date = date("Y-m-d");

        $string = date(empty($format) ? $default_format : $format, strtotime($date));

        $months = array("January"=>"января","February"=>"февраля","March"=>"марта","April"=>"апреля","May"=>"мая","June"=>"июня","July"=>"июля","August"=>"августа","September"=>"сентября","October"=>"октября","November"=>"ноября","December"=>"декабря");
        $string = str_replace(array_keys($months), array_values($months), $string);

        $short_months = array("Jan"=>"янв","Feb"=>"фев","Mar"=>"мар","Apr"=>"апр","May"=>"май","Jun"=>"июнь","Jul"=>"июль","Aug"=>"авг","Sep"=>"сен","Oct"=>"окт","Nov"=>"ноя","Dec"=>"дек");
        $string = str_replace(array_keys($short_months), array_values($short_months), $string);

        return $string;
    }

    public function time_modifier($date, $format = null)
    {
        return date(empty($format)?'H:i':$format, strtotime($date));
    }

    function size_modifier($size)
    {
        if($size >= 1<<30 && $size/(1<<30) > 1)
            return number_format($size/(1<<30),2)."GB";
        elseif($size >= 1<<20 && $size/(1<<20) > 1)
            return number_format($size/(1<<20))."MB";
        elseif($size >= 1<<10 && $size/(1<<10) > 1)
            return number_format($size/(1<<10))."KB";
        else
            return number_format($size)." bytes";
    }

    public function packer_plugin($params, $smarty)
    {
        if(!empty($params['var']))
        {
            $out_file = $this->custom->packer($params['files']);
            $smarty->assign($params['var'], $out_file);
        }
    }

    public function api_plugin($params, $smarty)
    {
        if(!isset($params['module']))
            return false;
        if(!isset($params['method']))
            return false;

        $module = $params['module'];
        $method = $params['method'];
        $var = $params['var'];
        unset($params['module']);
        unset($params['method']);
        unset($params['var']);

        $res = call_user_func_array(array($this->$module, $method), $params['arguments']);
        $smarty->assign($var, $res);
    }
}
