<?php
abstract class NodeSectionController extends Controller
{
    public $node_id;
    public $root_node_id;
    /** @var Node|null */
    private $_node;
    /** @var Node|null */
    public $_rootNode;

    public function init()
    {
        parent::init();
        if (isset($_GET['node_id'])) $this->node_id = $_GET['node_id'];
        else throw new CHttpException(500, 'node_id is not set');
        $this->root_node_id = $this->getNode()->node_id;
    }

    public function createUrl($route, $params = array(), $ampersand = '&')
    {
        if ($route === '') {
            $route = $this->getId() . '/' . $this->getAction()->getId();
            if (!isset($params['node_id']))
                $params['node_id'] = $this->node_id;
        } else if (strpos($route, '/') === false) {
            $route = $this->getId() . '/' . $route;
            if (!isset($params['node_id']))
                $params['node_id'] = $this->node_id;
        } else {
            if (substr($route,0, strlen($this->getId())) == $this->getId()) {
                if (!isset($params['node_id']))
                    $params['node_id'] = $this->node_id;
            }
        }
        return Yii::app()->createUrl(trim($route, '/'), $params, $ampersand);
    }

    /**
     * @return Node
     */
    public function getNode()
    {
        if(!isset($this->_node))
            $this->_node = Node::model()->with('i18n')->findByPk($this->node_id);
        return $this->_node;
    }
    /**
     * @return Node
     */
    public function getRootNode()
    {
        if(!isset($this->_rootNode))
            $this->_rootNode = Node::model()->with('i18n')->findByPk($this->root_node_id);
        return $this->_rootNode;
    }
}
