<?php

namespace Opentalent\OtTemplating\ViewHelpers\Request;

use Closure;
use Opentalent\OtCore\ViewHelpers\OtAbstractViewHelper;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;

/**
 *   Returns the current url with a 'page=' argument set up or updated
 *   Warning: this viewhelper will also add a 'no_cache=1' argument to the query
 *
 *     {namespace ot=Opentalent\OtTemplating\ViewHelpers}
 *
 *     {ot:request.withPage(page: 1)}
 *
 * @package Opentalent\OtTemplating\ViewHelpers
 */
class WithPageViewHelper extends OtAbstractViewHelper {

    /**
     * -- This method is expected by Fluid --
     * Declares the viewhelper's parameters
     */
    public function initializeArguments()
    {
        $this->registerArgument('page',
            'int',
            "The page's number",
            true);
        $this->registerArgument('nocache',
            'int',
            "If true, adds a no_cache parameter to the query",
            false,
            1
        );
    }

    /**
     * -- This method is expected by Fluid --
     * Renders the content as html
     *
     * @param array $arguments
     * @param Closure $renderChildrenClosure
     * @param RenderingContextInterface $renderingContext
     * @return string
     */
    public static function renderStatic(
        array $arguments,
        Closure $renderChildrenClosure,
        RenderingContextInterface $renderingContext
    ) {
        $page = $arguments['page'];
        $nocache = $arguments['nocache'];

        $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);
    }
}
