<?php

/**
 * Questo file è parte di Pongho.
 *
 * @author    Daniele De Nobili
 * @copyright Web Agency Meta Line S.r.l.
 * @package   Application\Admin
 */

namespace Application\Admin;

use Application\Admin\DependencyInjection\AdminBarServiceProvider;
use Application\Admin\DependencyInjection\AdminServicesProvider;
use Application\Admin\DependencyInjection\AdminSidebarServiceProvider;
use Application\Admin\DependencyInjection\DashboardWidgetsServiceProvider;
use Application\Admin\DependencyInjection\ResponseFactoryServiceProvider;
use Application\Admin\DependencyInjection\RoutingServiceProvider;
use Application\Admin\DependencyInjection\TemplatingServiceProvider;
use Application\Admin\DependencyInjection\WidgetsServiceProvider;
use Pongho\Core\Plugin;
use Pongho\Core\TemplateResponse;
use Pongho\EventDispatcher\Event;
use Pongho\Http\Response;

class Kernel extends Plugin
{
    public const VERSION = '1.0.0-dev';

    /**
     * @var \Application\Admin\AdminBar\AdminBar
     */
    protected $admin_bar;

    /**
     * @var \Application\Admin\Widget\WidgetsCollection
     */
    protected $admin_widgets;

    /**
     * {@inheritdoc}
     */
    public function load()
    {
        // Dependency Injection
        $this->container->register(new AdminSidebarServiceProvider());
        $this->container->register(new AdminServicesProvider());
        $this->container->register(new RoutingServiceProvider());
        $this->container->register(new AdminBarServiceProvider());
        $this->container->register(new WidgetsServiceProvider());
        $this->container->register(new DashboardWidgetsServiceProvider());
        $this->container->register(new ResponseFactoryServiceProvider());
        $this->container->register(new TemplatingServiceProvider());

        $this->connect('core.filter_response', 'addAdminBar');
    }

    /**
     * Risponde al filtro `core.filter_response` per aggiungere la barra di amministrazione alla risposta.
     *
     * @return \Pongho\Http\Response
     */
    public function addAdminBar(Event $event, Response $response)
    {
        /** @var \Pongho\Http\Request $request */
        $request = $this->container->get('request');

        if ($request->query->get('modal') || $request->isAjax()) {
            return $response;
        }

        if ($response instanceof TemplateResponse && $this->container->get('current_user')->hasPermit('admin')) {
            /** @var \Application\Admin\AdminBar\AdminBarRenderer $renderer */
            $renderer = $this->container->get('admin_bar_renderer');

            return $renderer->render($response);
        }

        return $response;
    }
}
