<?php

namespace Ig\IgReservations\ViewHelpers\Event;

use Ig\IgReservations\Domain\Model\BookingType;
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 BookingTypeForLanguageViewHelper 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('event', 'object', 'The event object', true);
        $this->registerArgument('language', 'int', 'The language UID', false, 0);
        $this->registerArgument(
            'as',
            'string',
            'The variable name to assign the BookingType object',
            false,
            'bookingType'
        );
    }

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

        $bookingType = $event->getBookingType();
        $localizedObject = $bookingType;

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

            $queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable(
                'tx_extension_domain_model_bookingtype'
            );
            $row = $queryBuilder->select('*')
                ->from('tx_extension_domain_model_bookingtype')
                ->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(BookingType::class, [$row]);
                $localizedObject = $res[0];
            }
        }

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

        $output = $this->renderChildren();

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

        return $output;
    }
}
