<?php

namespace Ig\IgReservations\ViewHelpers\Reservation;

use Ig\IgReservations\Domain\Model\ReservationType;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper;
use TYPO3Fluid\Fluid\Core\ViewHelper\AbstractViewHelper;

class ReservationTypeForLanguageViewHelper extends AbstractViewHelper
{
    protected $escapeOutput = false;
    
    /**
     * @var DataMapper
     */
    protected $dataMapper;

    public function injectDataMapper(DataMapper $dataMapper): void
    {
        $this->dataMapper = $dataMapper;
    }

    public function initializeArguments(): void
    {
        parent::initializeArguments();
        $this->registerArgument('reservation', 'object', 'The reservation object', true);
        $this->registerArgument(
            'as',
            'string',
            'The variable name to assign the ReservationType object',
            false,
            'reservationType'
        );
    }

    public function render()
    {
        $reservation = $this->arguments['reservation'];
        $event = $reservation->getEvent();
        $language = $reservation->getLanguage();
        $variableName = $this->arguments['as'];

        $reservationType = $reservation->getReservationType();
        $localizedObject = $reservationType;

        if ($reservationType && $language > 0) {
            $uid = $reservationType->getUid();

            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable(
                'tx_igreservations_domain_model_reservationtype'
            );
            $row = $queryBuilder->select('*')
                ->from('tx_igreservations_domain_model_reservationtype')
                ->where(
                    $queryBuilder->expr()
->or($queryBuilder->expr() ->eq('uid', $uid), $queryBuilder->expr() ->eq('l10n_parent', $uid)),
                    $queryBuilder->expr()
->eq('sys_language_uid', $language)
                )
                ->executeQuery()
                ->fetchAssociative();

            if ($row) {
                $res = $this->dataMapper->map(ReservationType::class, [$row]);
                $localizedObject = $res[0];
            }
        }

        if ($variableName) {
            $this->templateVariableContainer->add($variableName, $localizedObject);
        }

        $output = $this->renderChildren();

        if ($variableName) {
            $this->templateVariableContainer->remove($variableName);
        }

        return $output;
    }
}
