<?php

namespace App\Presenters;


use App\Components\Breadcrumb\Breadcrumb;
use App\Model\Exceptions\Translator\UnsupportedLanguageException;
use App\Model\Facades\TranslatorFacade;
use App\Model\Translator;
use App\Model\User;
use Doctrine\DBAL\Exception\TableNotFoundException;
use Nette\Application\UI\Presenter;
use Nette\Http\IResponse;
use Nette\Http\Request;
use Tracy\Debugger;
use WebChemistry\Images\TPresenter;


/**
 * Class BasePresenter
 * @property-read User $user
 */
abstract class BasePresenter extends Presenter
{
//    protected $publicAccess = false;
    protected $publicAccess = true;

    /** @persistent */
    public $locale;

    /** @var  Breadcrumb */
    protected $breadcrumb;

    /** @var  Request */
    protected $request;

    /** @var  Translator */
    protected $translator;

    /** @var  TranslatorFacade */
    protected $translatorFacade;

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

    use TPresenter;

    protected function startup()
    {
        parent::startup();

        if (!$this->user->isLoggedIn()) {
            if ($this->publicAccess === false) {    // presenter is not public
                $this->error(null, IResponse::S403_FORBIDDEN);
            } elseif (is_array($this->publicAccess) && !in_array($this->presenter->action, $this->publicAccess)) {  // action is not public
                $this->error(null, IResponse::S403_FORBIDDEN);
            }
        }

        $this->setupTranslator();

        $this->breadcrumb = new Breadcrumb($this, 'breadcrumb');
        $this->breadcrumb->setHomepage('homepage', '', 'Homepage:', ['siteId' => null])->setFaIcon('home');
    }

    public function injectBase(TranslatorFacade $translatorFacade, Translator $translator, Request $request)
    {
        $this->translatorFacade = $translatorFacade;
        $this->translator = $translator;
        $this->request = $request;
    }

    public function flashMessage($message, $type = 'info', $count = null, $disableTranslator = false)
    {
        if ($disableTranslator) {
            return parent::flashMessage($message, $type);
        }
        return parent::flashMessage($this->translator->translate($message, $count), $type);
    }

    public function handleLogout()
    {
        $this->user->logout(true);

        $this->redirect(':Front:Homepage:');
    }

    public function beforeRender()
    {
    	parent::beforeRender();
        $this->breadcrumbAddLinkToSelf();

        try {
            $this->template->supportedLocales = $this->translator->getSupportedLocales();
        } catch (TableNotFoundException $e) {
            // doctrine manager can be used without database
            $this->template->supportedLocales = [];
        }
        $this->template->locale = $this->locale;
        $this->template->faviconPath = __DIR__ . '/templates/includes/generated/favicon.latte';
        $this->template->baseTemplates = __DIR__ . '/templates';
        $this->template->includePath = __DIR__ . '/templates/includes';
        $this->template->pageHeader = $this->pageHeader;
        $this->template->breadcrumb = $this->breadcrumb;
    }

    protected function setupTranslator()
    {
        try {
            $supportedLocales = array_keys($this->translatorFacade->getLanguageReader()->getAvailableLanguagesPairs());
            if (!in_array($this->locale, $supportedLocales)) {
                $lang = $this->request->detectLanguage($supportedLocales);
                if ($lang) {
                    $this->locale = $lang;
                } else {
                    $this->locale = $this->translatorFacade->getLanguageReader()->getDefaultLanguage()->getIdentifier();
                }
            }
            $this->translator->setupLocale($this->locale);
        } catch (UnsupportedLanguageException $e) {
            // this should not happen
            Debugger::log($e);
            $this->error('Localization problem has occurred.', IResponse::S500_INTERNAL_SERVER_ERROR);
        }

        $this->template->setTranslator($this->translator);
    }

    protected function breadcrumbAddLinkToSelf()
    {
        if ($this->pageHeader) {
            $this->breadcrumb->addNode('selfLink', $this->pageHeader, ":{$this->getName()}:{$this->getAction()}", $this->getParameters());
        }
    }

}