<?php declare(strict_types=1);

namespace App\Twig\Extension;

use App\Tool\Utils;
use Pimcore\Model\Document\Editable\EditableInterface;
use Pimcore\Model\Document\Page;
use Pimcore\Templating\Renderer\EditableRenderer;
use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class DocExtension extends AbstractExtension
{
    protected EditableRenderer $editableRenderer;

    public function __construct(EditableRenderer $editableRenderer)
    {
        $this->editableRenderer = $editableRenderer;
    }

    public function getFunctions(): array
    {
        return [
            new TwigFunction('doc_url', [$this, 'docUrl'], ['needs_context' => true]),
            new TwigFunction('doc_url_by_id', [$this, 'docUrlById'], ['needs_context' => true]),
            new TwigFunction('doc_is_active', [$this, 'docIsActive'], ['needs_context' => true]),
            new TwigFunction('doc_editable', [$this, 'docEditable'], ['needs_context' => true, 'is_safe' => ['html']]),
            new TwigFunction('doc_pagination', [$this, 'docPagination']),
        ];
    }

    public function docUrl($context, $realFullPath): string
    {
        return Utils::docUrl($realFullPath, $context['language']);
    }

    public function docUrlById($context, $id): string
    {
        return Utils::docUrlById($id, $context['language']);
    }

    public function docIsActive($context, $id): bool
    {
        $document = $context['document'] ?? null;
        return $id && $document instanceof Page &&
            ($document->getId() == $id || $document->getContentMainDocumentId() == $id);
    }

    public function docEditable($context, $name, $type, $options = []): EditableInterface
    {
        $defaultConfigurations = [
            'input' => ['htmlspecialchars' => true],
            'numeric' => ['minValue' => 0],
            'textarea' => ['height' => 100, 'nl2br' => true, 'htmlspecialchars' => true],
            'wysiwyg' => ['height' => 100, 'inline' => true, 'enterMode' => 1, 'customConfig' => '/admin/js/cke_config_document_loader.js'],
            'image' => ['hidetext' => true, 'reload' => false, 'thumbnail' => 'AdminFallback', 'uploadPath' => '/dokumenty'],
            'multihref' => ['uploadPath' => '/dokumenty', 'thumbnail' => null],
            'relations' => ['uploadPath' => '/dokumenty', 'thumbnail' => null],
            'href' => [],
            'relation' => [],
            'checkbox' => ['reload' => false],
            'date' => ['format' => 'd.m.Y', 'startDay' => 1],
            'select' => ['reload' => false, 'store' => [['dummy', 'dummy']]],
            'table' => ['defaults' => ['cols' => 1, 'rows' => 1, 'data' => [['dummy']]]],
            'multiselect' => ['store' => [['dummy', 'dummy']]],
        ];

        if ($type === 'image' && $context['editmode']) {
            $defaultConfigurations['image']['width'] = 0;
        }

        $options = array_merge($defaultConfigurations[$type] ?? [], $options);
        return $this->editableRenderer->render($context['document'], $type, $name, $options, $context['editmode']);
    }

    public function docPagination(array $pagination): array
    {
        $urlFirst = $urlPrevious = $urlNext = $urlLast = 'javascript:void(0)';
        if (isset($pagination['previous']) && !isset($pagination['ajax'])) {
            $urlFirst = $pagination['urlprefix'] . $pagination['first'];
            $urlPrevious = $pagination['urlprefix'] . $pagination['previous'];
        }
        if (isset($pagination['next']) && !isset($pagination['ajax'])) {
            $urlNext = $pagination['urlprefix'] . $pagination['next'];
            $urlLast = $pagination['urlprefix'] . $pagination['last'];
        }

        $listBoundaryLength = 3;
        $listStart = max(1, $pagination['current'] - $listBoundaryLength);
        $listEnd = min($pagination['last'], $listStart + $listBoundaryLength * 2);
        $listStart = max(1, $listEnd - $listBoundaryLength * 2);

        return array_merge($pagination, [
            'isAjax' => isset($pagination['ajax']),
            'urlPrevious' => $urlPrevious,
            'urlFirst' => $urlFirst,
            'urlNext' => $urlNext,
            'urlLast' => $urlLast,
            'listBoundaryLength' => $listBoundaryLength,
            'listStart' => $listStart,
            'listEnd' => $listEnd,
        ]);
    }
}
