<?php

namespace Opentalent\OtTemplating\ViewHelpers;

use Opentalent\OtCore\ViewHelpers\OtAbstractViewHelper;

/**
 *
 * {namespace ot=Opentalent\OtTemplating\ViewHelpers}
 *
 * {ot:pagination(collection:collection)}
 *
 * @package Opentalent\OtTemplating\ViewHelpers
 */
class PaginationViewHelper extends OtAbstractViewHelper
{
    /**
     * >> Required to prevent typo3 to escape the html output
     * @var boolean
     */
    protected $escapeOutput = false;

    /**
     * -- This method is expected by Fluid --
     * Declares the viewhelper's parameters
     */
    public function initializeArguments()
    {
        $this->registerArgument(
            'collection',
            'object',
            'The ApiPagedCollection object',
            true
        );
    }

    /**
     * -- This method is expected by Fluid --
     * Renders the content as html
     *
     * @return string Rendered tag
     */
    public function render() {
        $collection = $this->arguments['collection'];
        $lastPage = $collection->getLastPage();
        $currentPage = $collection->getCurrentPage();

        if (!$lastPage > 0) {
            return "";
        }

        $divWrapper = '<div class="pagination-bar">%s</div>';

        $goToFirst = '<a href="' . $this->getUriWithPage(1) . '" ' .
            'title="' . $this->translate('go-to-first-page') . '">' .
            '<i class="fa fa-angle-double-left"></i>' .
            '</a>';
        $goToLast = '<a href="' . $this->getUriWithPage($lastPage) . '"' .
            'title="' . $this->translate('go-to-last-page') . '">' .
            '<i class="fa fa-angle-double-right"></i>' .
            '</a>';

        $startAt = $currentPage > 6  ? $currentPage - 5 : 1;
        $endAt = $currentPage < ($lastPage - 5) ? $currentPage + 5 : $lastPage;

        $ul = '<ul>';
        for ($i = $startAt; $i <= $endAt; $i++) {
            $ul .= '<li class="' . ($i == $currentPage ? 'current' : '') . '">';
            $ul .= '<a href="' . $this->getUriWithPage($i) . '" title="' . $this->translate('go-to-page') . $i .'">' . $i . '</a>';
            $ul .= '</li>';
        }
        $ul .= '</ul>';

        return sprintf($divWrapper, $goToFirst . $ul . $goToLast);
    }

    private function getUriWithPage(int $page, bool $nocache = true) {
        $request = $GLOBALS['TYPO3_REQUEST'];
        $uri = $request->getUri();
        $query = $uri->getQuery();

        if (preg_match("/.*page=\d+.*/", $query)) {
            $query = preg_replace(
                "/page=\d+/",
                "page=" . $page,
                $query
            );
        } elseif ($query != '') {
            $query .= "&page=" . $page;
        } else {
            $query .= "page=" . $page;
        }

        $query = preg_replace("/&no_cache=1/", "", $query);
        if ($nocache) {
            $query .= '&no_cache=1';
        }
        return (string)$uri->withQuery($query);
    }

}
