<?php

namespace Ig\IgReservations\ViewHelpers;

use Ig\IgReservations\Domain\Model\Calendar;
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 TYPO3\CMS\Fluid\Core\Rendering\RenderingContext;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;

class CalendarViewHelper extends AbstractViewHelper
{
    protected $escapeOutput = false;
    /**
     * Initialize arguments
     */
    public function initializeArguments()
    {
        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...');
    }
    /**
     * Static rendering
     */
    public static function renderStatic(
        array $arguments,
        \Closure $renderChildrenClosure,
        RenderingContextInterface $renderingContext
    ): string {
        $calendar = $arguments['calendar'];
        $ajaxPageType = (int) $arguments['ajaxPageType'];
        $ajaxPageUid = (int) $arguments['ajaxPageUid'];
        //$acl = $calendar->getAcl();

        /** @var RenderingContext $renderingContext */
        $fluidRenderingContext = $renderingContext;

        $request = $fluidRenderingContext->getRequest();
        $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 . '">' . $renderChildrenClosure() . '</div>';
    }
}
