<?php
/**
 * core.framework
 *
 * @category  Core
 * @package   Core_Application
 * @copyright Copyright (c) 2011. Burza d.o.o. (http://web.burza.hr/en/)
 * @license   proprietary
 */

/**
 * @category  Core
 * @package   Core_Application
 * @copyright Copyright (c) 2011. Burza d.o.o. (http://web.burza.hr/en/)
 * @license   proprietary
 */
class Core_Application_Plugin_EventHandler_TemplateFinder extends Core_Application_Plugin_EventHandler_Abstract
{
    /**
     * @var array
     */
    protected $_subscriptions = array(
        array(
            'event'    => Core_Dispatcher::EVENT_PREDISPATCH,
            'method'   => 'eventHandler',
            'priority' => -50,
        ),
    );

    /**
     * @var string
     */
    protected $_format;

    /**
     * @var Twig_LoaderInterface
     */
    protected $_viewLoader;

    /**
     * @param Twig_LoaderInterface $viewLoader
     *
     * @return \Core_Application_Plugin_EventHandler_TemplateFinder
     */
    public function setViewLoader(Twig_LoaderInterface $viewLoader)
    {
        $this->_viewLoader = $viewLoader;
        return $this;
    }

    /**
     * @return Twig_LoaderInterface
     */
    public function getViewLoader()
    {
        if (null === $this->_viewLoader) {
            $this->setViewLoader(Core_Application::get('ViewLoader'));
        }
        return $this->_viewLoader;
    }

    /**
     * @param Core_Event_Interface $event Event to handle
     * @param mixed                $data  Not used
     *
     * @return void
     */
    public function eventHandler(Core_Event_Interface $event, $data = null)
    {
        $viewLoader = $this->getViewLoader();
        if ($viewLoader instanceof Twig_Loader_Filesystem) {
            $location = $event->getParam('location');
            $finder   = $this->getResourceFinder();

            $path     = $finder->findTemplatesPath($location);
            $paths    = $viewLoader->getPaths();
            if (!in_array($path, $paths) && array_unshift($paths, $path)) {
                $viewLoader->setPaths($paths);
            }
        }
    }
}
