<?php

/**
 * Created by PhpStorm.
 * User: hanz
 * Date: 29.4.14
 * Time: 14:49s.
 */
class Base
{
    protected $smarty;
    protected $template;

    public function init_smarty()
    {
        $this->smarty = createSmarty(true, true);
    }

    public function getTemplate()
    {
        if (empty($this->template)) {
            throw new Exception('Empty template name');
        }

        return $this->template;
    }

    public function setTemplate($name)
    {
        $this->template = $name;
    }

    public static function getClassName()
    {
        $className = explode('\\', get_called_class());

        return end($className);
    }

    public function display()
    {
        $this->smarty->display($this->getTemplate());
    }

    public function handle()
    {
        $acn = getVal('acn');
        if ($acn) {
            $action = 'handle'.ucfirst($acn);
            if (method_exists($this, $action)) {
                call_user_func([$this, $action]);
            }
        }
    }

    public function run()
    {
        // Process POSTEd values
        $this->handle();

        // Collect template variables
        $vars = $this->collectVariables();

        // Init templating system
        $this->init_smarty();

        // Assign template variables to template
        $this->assign_($vars);

        // Render template
        $this->display();
    }

    protected function collectVariables()
    {
        return $this->get_vars();
    }

    protected function get_vars()
    {
        return [
            'view' => $this,
        ];
    }

    public function getPageHandler()
    {
        return getVal('s');
    }

    public function assign_($array)
    {
        $this->smarty->assign($array);
    }
}
