<?php

namespace Opentalent\OtTemplating\ViewHelpers\Events;

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

/**
 *   This view helper returns the Event object matching the given id
 *
 *     {namespace ot=Opentalent\OtTemplating\ViewHelpers}
 *
 *     <ot:events.getById as="event"
 *                       eventId="1">
 *          <f:debug>{event}</f:debug>
 *     </ot:events.getById>
 *
 * @package Opentalent\OtTemplating\ViewHelpers
 */
class GetByIdViewHelper extends OtAbstractViewHelper {

    use TemplateVariableViewHelperTrait;

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

    /**
     * @var EventRepository
     */
    protected EventRepository $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(
            'eventId',
            'integer',
            'Id of the event',
            true
        );
    }

    /**
     *  -- This method is expected by Fluid --
     * Renders the content as html
     *
     * @return string
     * @throws ApiRequestException
     */
    public function render()
    {
        $as = $this->arguments['as'];
        $eventId = $this->arguments['eventId'];

        try {
            $event = $this->eventRepository->findById($eventId);
        } catch (ApiRequestException $e) {
            OtLogger::error(sprintf('API Error: %s', $e->getMessage()));
            $event = new Event();
            $event->setName("<Erreur>");
            $event->setDescription("Une erreur s'est produite et ne permet pas l'affichage de cet évènement. Veuillez nous excusez pour la gêne occasionnée.");
        }

        if ($event === null) {
            $event = new Event();
            $event->setName("(Évènement supprimé)");
        }

        $variables = [$as => $event];
        return $this->renderChildrenWithVariables($variables);
    }

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