<?php

namespace Velis\Mvc\View;

use Laminas\View\Model\ViewModel;
use UnexpectedValueException;
use Velis\App;
use Velis\Filter;
use Velis\Model\BaseModel;
use Velis\Mvc\View\Engine\EngineInterface;

/**
 * Base class for layout boxes
 * @author Olek Procki <olo@velis.pl>
 */
abstract class AbstractBox extends BaseModel
{
    protected function _getData(): ViewModel
    {
        return new ViewModel();
    }

    /**
     * Reads required data & returns valid view model
     *
     * @throws UnexpectedValueException
     */
    final public function getModel(): ViewModel
    {
        $result = $this->_getData();

        $classParts = explode('\\', get_class($this));

        $module = reset($classParts);
        $box    = end($classParts);

        $result->setTemplate(
            MODULE_PATH . $module . '/view/box/' . strtolower(Filter::filterToDash($box)) . '.tpl'
        );

        $result->options = $this->_params;
        $result->widget  = $this;

        return $result;
    }


    /**
     * Renders box contents
     *
     * @throws UnexpectedValueException
     */
    final public function __invoke(): string
    {
        /** @var EngineInterface $view */
        $view = App::getService('SmartyRenderer');
        $model = $this->getModel();

        $view->assign($model->getVariables()->getArrayCopy());

        return $view->fetch($model->getTemplate());
    }
}
