<?php
/**
 * @package    pixelcms_articles
 *
 * @author     christophf <your@email.com>
 * @copyright  A copyright
 * @license    GNU General Public License version 2 or later; see LICENSE.txt
 * @link       http://your.url.com
 */

use Joomla\CMS\MVC\Controller\BaseController;
use Joomla\Registry\Registry;

defined('_JEXEC') or die;

/**
 * Pixelcms_articles Controller.
 *
 * @package  pixelcms_articles
 * @since    1.0
 */
class Pixelcms_articlesController extends BaseController
{
	protected $default_layout = 'default';
	protected static $views;
	protected $is_module = false;
	protected $module_name;
	protected $query;
	protected $params;

	/*
	 * Dies musste überschrieben werden damit die Views das Layout berücksichtigen beim Cachen
	 */
	public function getView($name = '', $type = '', $prefix = '', $config = array())
	{
		// @note We use self so we only access stuff in this class rather than in all classes.
		if (!isset(self::$views))
		{
			self::$views = array();
		}

		if (empty($name))
		{
			$name = $this->getName();
		}

		if (empty($prefix))
		{
			$prefix = $this->getName() . 'View';
		}

		if (empty(self::$views[$name][$type][$prefix][$config['layout']]))
		{
			if ($view = $this->createView($name, $prefix, $type, $config))
			{
				self::$views[$name][$type][$prefix][$config['layout']] = & $view;
			}
			else
			{
				throw new \Exception(\JText::sprintf('JLIB_APPLICATION_ERROR_VIEW_NOT_FOUND', $name, $type, $prefix), 404);
			}
		}

		return self::$views[$name][$type][$prefix][$config['layout']];
	}

    protected function populateState()
    {
        $app = JFactory::getApplication('site');

        // Load the parameters.
        /** @var Registry $params */
        $params = $app->getParams();
        $query = $this->getQuery();
        $globalParams = JComponentHelper::getParams('com_pixelcms_articles');
        $input = ($this->input) ? $this->input->getArray() : [];

        $this->params = $params = new Registry(self::mergeStates([], $globalParams->toArray(), $params->toArray(), $query->toArray(), $input));
    }

    private static function mergeStates(...$states)
    {
        $states = array_map(function($state) {
            return array_filter($state, function($stateValue) {
                return $stateValue !== null;
            });
        }, $states);
        return array_merge(...$states);
    }

    private function getQuery()
    {
        $app = JFactory::getApplication('site');

        if (!$this->query)
        {
            if ($this->input && $Itemid = $this->input->getInt('Itemid')) {
                $this->query = new Registry(array_merge([], $app->getMenu()->getItem($Itemid)->query));
            } else {
                $this->query = new Registry(array_merge([], $app->getMenu()->getActive()->query));
            }
        }

        return $this->query;
    }

	/*
	 * Dies musste überschrieben werden damit die Views das Layout berücksichtigen beim Cachen
	 */
	public function display($cachable = false, $urlparams = array())
	{
		$document = \JFactory::getDocument();
		$app = \JFactory::getApplication();
		$viewType = $document->getType();

		$this->populateState();

		$viewName = $this->params->get('view', $this->default_view);
		$modelName = $this->params->get('model', $viewName);
		$viewLayout = $this->params->get('layout', $this->default_layout, 'string');

		$view = $this->getView($viewName, $viewType, '', array('base_path' => $this->basePath, 'layout' => $viewLayout));
		$view->item_id = $this->input->get('Itemid');

		if ($this->is_module) {
            $view->addTemplatePath(JPATH_THEMES . DS . $app->getTemplate() . DS . 'html' . DS . $this->module_name . DS . $viewName);
            $view->set('is_module', true);
        }

		// Get/Create the model
		if ($model = $this->getModel($modelName))
		{
			// Push the model into the view (as default)
			$view->setModel($model, true);
		}

		$view->document = $document;

		// Display the view
		if ($cachable && $viewType !== 'feed' && \JFactory::getConfig()->get('caching') >= 1)
		{
			$option = $this->input->get('option');

			if (is_array($urlparams))
			{
				$app = \JFactory::getApplication();

				if (!empty($app->registeredurlparams))
				{
					$registeredurlparams = $app->registeredurlparams;
				}
				else
				{
					$registeredurlparams = new \stdClass;
				}

				foreach ($urlparams as $key => $value)
				{
					// Add your safe URL parameters with variable type as value {@see \JFilterInput::clean()}.
					$registeredurlparams->$key = $value;
				}

				$app->registeredurlparams = $registeredurlparams;
			}

			try
			{
				/** @var \JCacheControllerView $cache */
				$cache = \JFactory::getCache($option, 'view');
				$cache->get($view, 'display');
			}
			catch (\JCacheException $exception)
			{
				$view->display();
			}
		}
		else
		{
			$view->display();
		}

		return $this;
	}

    public function load($type)
    {
        return $this->getModel($type);
    }
}
