<?php

namespace Ig\IgReservations\ViewHelpers;

use Ig\IgReservations\Domain\Model\Calendar;
use Psr\Http\Message\ServerRequestInterface;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Mvc\ExtbaseRequestParameters;
use TYPO3\CMS\Extbase\Mvc\Request;
use TYPO3\CMS\Extbase\Mvc\Web\Routing\UriBuilder;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;

class CalendarViewHelper extends AbstractViewHelper
{
    protected $escapeOutput = false;
    /**
     * Initialize arguments
     */
    public function initializeArguments(): void
    {
        parent::initializeArguments();
        $this->registerArgument('calendar', Calendar::class, 'Calendar', true);
        $this->registerArgument('ajaxPageUid', 'int', 'ajaxPageUid', true);
        $this->registerArgument('ajaxPageType', 'int', 'ajaxPageType', false, 9_190_501);
        $this->registerArgument('class', 'string', 'class', false, '');
        $this->registerArgument('loading', 'string', 'Loading html', false, 'Loading...');
    }

    public function render(): string
    {
        $arguments = $this->arguments;
        $calendar = $arguments['calendar'];
        $ajaxPageType = (int) $arguments['ajaxPageType'];
        $ajaxPageUid = (int) $arguments['ajaxPageUid'];
        //$acl = $calendar->getAcl();

        $request = $this->renderingContext->getAttribute(ServerRequestInterface::class);
        $extbaseRequest = new Request($request->withAttribute('extbase', new ExtbaseRequestParameters()));
        
        $uriBuilder = GeneralUtility::makeInstance(UriBuilder::class);
        $uriBuilder->setRequest($extbaseRequest);
        
        //$controllerContext=$renderingContext->
        //$uriBuilder = $controllerContext->getUriBuilder()->reset();
        if ($ajaxPageUid) {
            $uriBuilder->setTargetPageUid((int)$ajaxPageUid);
        }

        $uriBuilder->setTargetPageType((int)$ajaxPageType);
        $uri = $uriBuilder->build();//uriFor( null, null, null, 'IgReservations', 'Ajax' );

        $class = 'calendar calendar-' . $calendar->getUid() . ' ' . $calendar->getViewDaysClass();
        if ($arguments['class']) {
            $class .= ' ' . $arguments['class'];
        }
        
        return '<div data-url="' . $uri . '" data-calendar="' . $calendar->getUid() . '" data-loading="' . htmlspecialchars(
            (string) $arguments['loading']
        ) . '" class="' . $class . '">' . $this->renderChildren() . '</div>';
    }
}
