<?php

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

namespace Application\Admin\Controller;

use Application\Core\BaseController;
use Pongho\Core\TemplateResponse;
use Pongho\Http\Exception\HttpException;
use Pongho\Http\Exception\HttpUnauthorizedException;
use Pongho\Http\Response;
use Pongho\Utilities\IniConfig;

/**
 * Controller base per l’amministrazione.
 */
abstract class AdminController extends BaseController
{
    /**
     * {@inheritdoc}
     */
    protected function handleInvalidResponse($response): Response
    {
        return new TemplateResponse($this->getHelper()->getView(), $this->getHelper()->getResponseHeaders());
    }

    /**
     * Numero di record per pagina da visualizzare negli elenchi.
     *
     * @var integer
     */
    protected $records_per_page = 50;

    /**
     * {@inheritdoc}
     */
    protected function boot()
    {
        parent::boot();

        // Utente loggato?
        if (!$this->getHelper()->getUser()->isLogged()) {
            /** @var \Application\Core\Model\Site $main_site */
            $main_site = $this->getContainer()->get('main_site');

            $qs = http_build_query(['redirect' => $this->currentUrl('&')], '', '&');
            $login_url = $main_site->domain() . '/user/login/?' . $qs;

            // Solo le azioni possono restituire risposte.
            // Quindi  la imposto.
            $this->setResponse($this->getHelper()->redirectResponse($login_url));

            return;
        }

        // Permesso consentito?
        if (!$this->getHelper()->getUser()->hasPermit('admin')) {
            throw new HttpUnauthorizedException();
        }

        // Aggiorno i servizi nella dependency injection
        $this->container->set('template_engine', $this->getHelper()->getBodyView());
        $this->container->set('admin_view_header', $this->getHelper()->getHeaderView());
        $this->container->set('admin_view_body', $this->getHelper()->getBodyView());
        $this->container->set('admin_view_footer', $this->getHelper()->getFooterView());

        // css e js
        $this->getHelper()->addJavaScriptInline($this->getJavascriptInline());
    }

    /**
     * {@inheritdoc}
     */
    protected function handleRaw($action_method)
    {
        try {
            return parent::handleRaw($action_method);
        } catch (HttpException $httpException) {
            switch ($httpException->getStatusCode()) {
                case 401:
                case 404:
                    $template = __DIR__ . '/../Resources/views/' . $httpException->getStatusCode() . '.php';
                    break;

                default:
                    $template = __DIR__ . '/../Resources/views/400.php';
                    $this->getHelper()->getBodyView()->assignVar('exception', $httpException);
                    break;
            }

            $this->getHelper()->getBodyView()->setTemplatePath($template);

            return new TemplateResponse($this->getHelper()->getView());
        }
    }

    /**
     * Restituisce l'helper per l'admin.
     *
     * @return \Application\Admin\Utilities\AdminControllerHelper
     */
    public function getHelper()
    {
        return $this->container->get('admin_controller_helper');
    }

    /**
     * {@inheritdoc}
     *
     * @deprecated
     */
    public function getView()
    {
        return $this->getHelper()->getView();
    }

    /**
     * @return \Pongho\Template\ViewInterface
     *
     * @deprecated
     */
    public function getHeaderView()
    {
        return $this->getHelper()->getHeaderView();
    }

    /**
     * @return \Pongho\Template\ViewInterface
     *
     * @deprecated
     */
    public function getBodyView()
    {
        return $this->getHelper()->getBodyView();
    }

    /**
     * @return \Pongho\Template\ViewInterface
     *
     * @deprecated
     */
    public function getFooterView()
    {
        return $this->getHelper()->getFooterView();
    }

    /**
     * @deprecated
     */
    protected function getViewGlobalVariables()
    {
        return $this->getHelper()->getViewGlobalVariables();
    }

    /**
     *
     */
    protected function getJavascriptInline()
    {
        $translator = $this->getHelper()->getTranslator();

        $pongho = [
            'action'      => $this->getAction(),
            'apiUrl'      => url('/api'),
            'maxFileSize' => (new IniConfig())->getMaxFileSize(), // TODO: Spostare nella dependency injection
            'lang'        => [
                'fileUploadErrors' => [
                    'maxFileSize'      => $translator->trans('The file size is too big'),
                    'minFileSize'      => $translator->trans('The file size is too small'),
                    'acceptFileTypes'  => $translator->trans('Extension not allowed'),
                    'maxNumberOfFiles' => $translator->trans('The total number of files exceed the limit'),
                    'uploadedBytes'    => $translator->trans('The total size of the files exceed the limit'),
                    'emptyResult'      => $translator->trans('The file looks empty'),
                ],
            ],
            'chosen'      => [
                'include_group_label_in_selected' => true,
                'no_results_text'                 => $translator->trans('No results match'),
                'placeholder_text_multiple'       => $translator->trans('Select Some Options'),
                'placeholder_text_single'         => $translator->trans('Select an Option'),
            ],
        ];

        $this->getHelper()->filter($this, 'admin.filter_js_pongho_var', $pongho);

        $pongho = json_encode($pongho);

        return <<<JS
var tmp = {$pongho},
    Pongho = window.Pongho || {};

for (var property in tmp) {
    if (tmp.hasOwnProperty(property)) {
        Pongho[property] = tmp[property];
    }
}
JS;
    }

    /**
     * Restituisce il modulo amministrativo.
     *
     * @return \Application\Admin\Model\AdminModule
     *
     * @deprecated
     */
    public function getAdminModule()
    {
        return $this->getParameter('admin_module');
    }

    /**
     * Restituisce l’ID del modulo amministrativo.
     *
     * @return integer
     *
     * @deprecated
     */
    public function getAdminModuleId()
    {
        return $this->getParameter('admin_module')->id;
    }

    /**
     * Restituisce l’ID del modulo.
     *
     * @return integer
     */
    public function getModuleId()
    {
        return $this->getParameter('module_id');
    }

    /**
     * Restituisce il modello ModuleSite corrente.
     *
     * @param boolean $thrown
     * @return \Application\Core\Model\ModuleSite
     * @throws \UnexpectedValueException Quando il modulo amministrativo non è associato ad alcun modulo.
     *
     * @deprecated
     */
    public function getSiteModule($thrown = true)
    {
        return $this->getHelper()->getModuleSite($thrown);
    }

    /** @var int */
    protected $content_language;

    /**
     * Restituisce la lingua per l'interfaccia
     * @return int
     *
     * @deprecated
     */
    public function getContentLanguageId()
    {
        /** @var \Application\Admin\Utilities\ContentLanguage $content_language */
        $content_language = $this->getContainer()->get('content_language');

        return $content_language->getId();
    }

    /**
     * {@inheritdoc}
     *
     * @deprecated
     */
    protected function getSiteModuleClassName()
    {
        return $this->getHelper()->getModuleSiteClass();
    }

    /**
     * Estende la funzione pongho_url() per aggiungere la query con il sito e la lingua corrente.
     *
     * Se questo metodo viene usato assieme alla risposta `Pongho\Http\RedirectResponse` si consiglia di usare il
     * carattere `&` come argomento per `$arg_separator`.
     *
     * @param string $url           Indirizzo da elaborare.
     * @param string $arg_separator Separatore dei valori.
     * @return string
     * @throws \InvalidArgumentException Se l’indirizzo passato contiene il prefisso `/pongho/`
     */
    public function url($url, $arg_separator = '&amp;')
    {
        /** @var \Application\Admin\Utilities\PonghoUrl $pongho_url */
        $pongho_url = $this->getContainer()->get('pongho_url');

        return $pongho_url->url($url, $arg_separator);
    }

    /**
     * Restituisce l'url corrente.
     *
     * @param string $arg_separator
     * @return string
     */
    public function currentUrl($arg_separator = '&amp;')
    {
        /** @var \Application\Admin\Utilities\PonghoUrl $pongho_url */
        $pongho_url = $this->getContainer()->get('pongho_url');

        return $pongho_url->currentUrl($arg_separator);
    }
}
