<?php

namespace Opentalent\OtTemplating\ViewHelpers\Events;

use FluidTYPO3\Vhs\Traits\TemplateVariableViewHelperTrait;
use Opentalent\OtCore\Domain\Repository\ApiPagedCollection;
use Opentalent\OtCore\Logging\OtLogger;
use Opentalent\OtCore\ViewHelpers\OtAbstractViewHelper;
use Opentalent\OtCore\Domain\Repository\EventRepository;
use Opentalent\OtCore\Exception\ApiRequestException;

/**
 *   This view helper give access to an ApiPagedCollection named according to the 'as' variable
 *   and containing all the upcoming events of the structure
 *
 *     {namespace ot=Opentalent\OtTemplating\ViewHelpers}
 *
 *     <ot:events.getAll as="events"
 *                        organizationId="{settings.organizationId}">
 *          <f:debug>{events}</f:debug>
 *     </ot:events.getAll>
 *
 * @package Opentalent\OtTemplating\ViewHelpers
 */
class GetAllViewHelper extends OtAbstractViewHelper {

    use TemplateVariableViewHelperTrait;

    /**
     * >> Required to prevent typo3 to escape the html output
     * @var boolean
     */
    protected $escapeOutput = false;

    /**
     * @var EventRepository
     *
     */
    protected $eventRepository;

    /**
     * -- This method is expected by Fluid --
     * Declares the viewhelper's parameters
     */
    public function initializeArguments()
    {
        $this->registerArgument(
            'as',
            'string',
            'Name of the returned array',
            true
        );
        $this->registerArgument(
            'organizationId',
            'integer',
            'Id of the current structure',
            true
        );
        $this->registerArgument(
            'fromChildren',
            'bool',
            'Get events from children instead',
            false,
            0
        );
    }

    /**
     * -- This method is expected by Fluid --
     * Renders the content as html
     *
     * @return string
     * @throws ApiRequestException|\Exception
     */
    public function render()
    {
        // Get current settings
        $as = $this->arguments['as'];
        $organizationId = $this->arguments['organizationId'];
        $fromChildren = $this->arguments['fromChildren'];

        $searchParams = [];

        if(isset($_REQUEST['search-loc']) && $_REQUEST['search-loc']) {
            $searchParams['where'] = $_REQUEST['search-loc'];
        }
        if(isset($_REQUEST['search-name']) && $_REQUEST['search-name']) {
            $searchParams['what'] = $_REQUEST['search-name'];
        }
        if(isset($_REQUEST['search-datestart']) && $_REQUEST['search-datestart']) {
            $dateStart = \DateTime::createFromFormat('d/m/Y', $_REQUEST['search-datestart']);
            $searchParams['datetimeStart'] = $dateStart->format('d-m-Y');
        }
        if(isset($_REQUEST['search-dateend']) && $_REQUEST['search-dateend']) {
            $dateEnd = \DateTime::createFromFormat('d/m/Y', $_REQUEST['search-dateend']);
            $searchParams['datetimeEnd'] = $dateEnd->format('d-m-Y');
        }

        if ($fromChildren) {
            $searchParams['children'] = '1';
        }
        if (isset($_REQUEST['page']) && $_REQUEST['page']) {
            $searchParams['page'] = $_REQUEST['page'];
        }

        try {
            $events = $this->eventRepository->searchBy($organizationId, $searchParams);
        } catch (ApiRequestException $e) {
            OtLogger::error(sprintf('API Error: %s', $e->getMessage()));
            $events = new ApiPagedCollection(0, 0, 1, []);
        }
        $variables = [$as => $events];
        return $this->renderChildrenWithVariables($variables);
    }

    /**
     * @param EventRepository $eventRepository
     */
    public function injectEventRepository(EventRepository $eventRepository)
    {
        $this->eventRepository = $eventRepository;
    }
}
