<?php
namespace Backend\BaseBundle\Event\Controller;

use Backend\BaseBundle\Service\FunctionCheckerServiceInterface;
use Symfony\Component\EventDispatcher\Event;
use Backend\BaseBundle\Model\SiteUser;

class MenuEvent extends Event
{
    const EVENT_MENU = 'event.controller.menu';

    /** @var  SiteUser */
    protected $user;

    protected $requestRouteName;

    protected $requestRouteParams;

    protected $menuConfigs = array();

    /** @var FunctionCheckerServiceInterface  */
    protected $functionChecker;

    public function __construct(SiteUser $user, $requestRouteName, $requestRouteParams, FunctionCheckerServiceInterface $functionChecker = null)
    {
        $this->user = $user;
        $this->requestRouteName = $requestRouteName;
        $this->requestRouteParams = $requestRouteParams;
        $this->functionChecker = $functionChecker;
    }

    public function getRequestRouteName()
    {
        return $this->requestRouteName;
    }

    /**
     * @return SiteUser
     */
    public function getUser()
    {
        return $this->user;
    }

    public function addMenu($controllerName, $menuConfig)
    {
        list($bundleName, $controllerShortName) = explode(':', $controllerName);
        if($this->functionChecker->isBundleEnabled($bundleName)){
            $this->menuConfigs[] = $menuConfig;
        }
    }

    public function getMenuConfigs()
    {
        $configs = array();
        foreach($this->menuConfigs as $config){
            $configs = array_merge_recursive($configs, $config);
        }

        foreach($configs as $name => $entry){
            if(is_array($entry['class'])){
                $configs[$name]['class'] = $entry['class'][0];
            }
            if(is_array($entry['active'])){
                $configs[$name]['active'] = array_sum($entry['active'])>0;
            }
        }
        return $configs;
    }

    /**
     * @return array | null
     */
    public function getRequestRouteParams()
    {
        return $this->requestRouteParams;
    }

}