<?php declare(strict_types=1);

namespace App\Twig\Extension;

use Twig\Extension\AbstractExtension;
use Twig\TwigFunction;

class PaginationExtension extends AbstractExtension
{
    public function getFunctions(): array
    {
        return [
            new TwigFunction('pagination', [$this, 'getPagination']),
        ];
    }

    public function getPagination(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,
        ]);
    }
}
