<?php

namespace Sso\Webservices\ObjectBundle\Events\Subscriber;

use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\FilterControllerEvent;
use Sso\Webservices\ObjectBundle\Events\Events;
use Symfony\Component\HttpKernel\Event\PostResponseEvent;
use Sso\ApiBundle\Api\Manager as ApiManager;
use Sso\Webservices\ObjectBundle\Worker\Factory as WorkerFactory;
use Sso\Webservices\ObjectBundle\Model\Request\Object\TreeView\Show as TreeViewShow;

class KernelSubscriber implements EventSubscriberInterface
{
    /**
     * @var ApiManager
     */
    private $apiM;

    /**
     * @var array
     */
    private $api;

    /**
     * @var TreeViewShow
     */
    private $treeViewShowModel;

    /**
     * @return WorkerFactory
     */
    public function worker()
    {
        if (!isset($this->api['worker'])) {
            $this->api['worker'] = new WorkerFactory($this->apiM);
        }
        return $this->api['worker'];
    }

    /**
     * KernelSubscriber constructor.
     * @param ApiManager $apiM
     */
    public function __construct(ApiManager $apiM)
    {
        $this->apiM = $apiM;
        $this->treeViewShowModel = new TreeViewShow($this->apiM);

    }

    /**
     * @return array The event names to listen to
     */
    public static function getSubscribedEvents()
    {
        return [
            Events::KERNEL_TERMINATE => ['objTreeIdReGen', 1024]
        ];
    }

    /**
     * Event subscriber to automate some controller tasks
     *
     * @param PostResponseEvent $event
     */
    public function objTreeIdReGen(PostResponseEvent $event)
    {
        $triggerControllerActions = [
            'Sso\Webservices\ObjectBundle\Controller\ObjectController::addAction',
            'Sso\Webservices\ObjectBundle\Controller\ObjectController::deleteAction',
            'Sso\Webservices\ObjectBundle\Controller\ObjectController::updateAction'
        ];

        if (in_array($event->getRequest()->attributes->get('_controller'), $triggerControllerActions)) {
            $treeIdGen = $this->apiM->container->get('object_event_treeids_regenerate');
            $treeIdGen->refreshTreeIdNumbers();
        }
    }
}
