<?php

namespace Comitium5\DesignerBundle\Twig\Extension;

use Comitium5\DesignerBundle\Entity\User;
use Comitium5\DesignerBundle\Helper\CKEditor\CkAssetHelper;
use Comitium5\DesignerBundle\Form\Manager\UniqueFormManager;
use Comitium5\DesignerBundle\Provider\SubsiteProvider;
use Symfony\Component\Form\FormView;
use Symfony\Component\HttpFoundation\Request;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

/**
 * Class CoreExtension
 *
 * @author Carles Gómez <carles@bab-soft.com>
 * @package Comitium5\DesignerBundle\Twig\Extension
 */
class CoreExtension extends AbstractExtension
{
    /**
     * @var SubsiteProvider
     */
    private $subsiteProvider;

    /**
     * @var UniqueFormManager
     */
    private $uniqueFormManager;

    /**
     * @var Request
     */
    private $masterRequest;

    /**
     * CoreExtension constructor.
     *
     * @param SubsiteProvider $subsiteProvider
     * @param UniqueFormManager $uniqueFormManager
     */
    public function __construct(
        SubsiteProvider $subsiteProvider,
        UniqueFormManager $uniqueFormManager
    ) {
        $this->subsiteProvider = $subsiteProvider;
        $this->uniqueFormManager = $uniqueFormManager;
    }

    /**
     * @return array|TwigFunction[]
     */
    public function getFunctions()
    {
        return [
            new TwigFunction('get_class', array($this, 'getClass')),
            new TwigFunction('get_locales', array($this, 'getLocales')),
            new TwigFunction('get_document_ico', array($this, 'getDocumentIco')),
            new TwigFunction('edit_asset_url', array($this, 'generateEditAssetUrl')),
            new TwigFunction('get_subsite_acronym', array($this, 'getSubsiteAcronym')),
            new TwigFunction('get_class', [$this, 'getClass']),
            new TwigFunction('get_locales', [$this, 'getLocales']),
            new TwigFunction('form_referer', [$this, 'getFormReferer']),

        ];
    }

    /**
     * @param $entity
     *
     * @return false|string|void
     */
    public function getClass($entity)
    {
        if (!is_object($entity)) {
            return;
        }

        return \get_class($entity);
    }

    /**
     * @return array
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function getLocales()
    {
        return $this
            ->subsiteProvider
            ->getSubsiteLocales();
    }

    /**
     * @param null $fileName
     * @return string
     */
    public function getDocumentIco($fileName = null)
    {
        $ico = "asset-docs.gif";

        if ($fileName === null) {
            return $ico;
        }

        $fileInfo = pathinfo($fileName);

        switch($fileInfo["extension"]) {
            case "pdf":
                $ico = "asset-docs-pdf.gif";
                break;
            case "doc":
            case "docx":
                $ico = "asset-docs-word.gif";
                break;
            case "xsl":
            case "xslx":
                $ico = "asset-docs-excel.gif";
                break;
            case "epub":
                $ico = "asset-docs-epub.gif";
                break;
            case "azw":
            case "azw3":
                $ico = "asset-docs-azw.gif";
                break;
            case "mobi":
                $ico = "asset-docs-mobi.gif";
                break;
        };

        return $ico;
    }

    /**
     * @param string $backEndUrl
     * @param string $locale
     * @param int $assetId
     *
     * @return string
     */
    public function generateEditAssetUrl(string $backEndUrl, string $locale, int $assetId, User $user)
    {
        return CkAssetHelper::prepareEditUrl(
            $backEndUrl,
            $locale,
            $assetId,
            $user->getToken()
        );
    }

    /**
     * @return string
     * @throws \Exception
     */
    public function getSubsiteAcronym(): string
    {
        return $this
            ->subsiteProvider
            ->getSubsite()
            ->getAcronym();
    }

    /**
     * @param  FormView $formView
     * @param  null $defaultUrl
     *
     * @return mixed|null
     */
    public function getFormReferer(FormView $formView, $defaultUrl = null)
    {
        if (!$this->masterRequest) {
            return $defaultUrl;
        }

        $ignoreReferer = $this->masterRequest->get("ignoreReferer", null);
        $contentLocale = $this->masterRequest->get("contentLocale", null);
        $isDraft = $this->masterRequest->get("draft", null);

        $isDraftReferer = preg_match(
                "/.+\?draft=\d+/",
                $this->masterRequest->headers->get("referer", "")
            ) === 1;

        if (($ignoreReferer !== null || $contentLocale !== null || $isDraft !== null || $isDraftReferer) && $defaultUrl !== null) {
            return $defaultUrl;
        }

        if (empty($formView['_uniqid'])) {
            return $defaultUrl;
        }

        $uniqueFormView = $formView['_uniqid'];

        return $this
            ->uniqueFormManager
            ->getSession()
            ->get(
                $this
                    ->uniqueFormManager
                    ->getFQDN(
                        $uniqueFormView->vars['value'],
                        'HTTP_REFERER'),
                $defaultUrl);
    }
}
