<?php

namespace Ig\IgReservations\Command;

use Ig\IgReservations\Domain\Repository\EventRepository;
use Ig\IgReservations\Service\MailService;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use TYPO3\CMS\Core\Core\Bootstrap;
use TYPO3\CMS\Core\Http\ServerRequestFactory;
use TYPO3\CMS\Core\Site\SiteFinder;
use TYPO3\CMS\Core\Utility\GeneralUtility;

use TYPO3\CMS\Extbase\Configuration\ConfigurationManager;
use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;
use TYPO3\CMS\Extbase\Service\EnvironmentService;

class AlarmCommand extends Command
{
    protected EventRepository $eventRepository;

    public function injectEventRepository(EventRepository $eventRepository)
    {
        $this->eventRepository = $eventRepository;
    }

    /**
     * Configure the command by defining the name, options and arguments
     */
    protected function configure()
    {
        $this->setDescription('Alarm email for events that are more than a week without an assigned teammember');
        $this->setHelp('Alarms the admin that an event has no assigned teammember');
    }

    /**
     * Executes the command for showing sys_log entries
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);
        //$io->title($this->getDescription());
        //$io->writeln($this->getHelp());
        Bootstrap::initializeBackendAuthentication();


        $configurationManager = GeneralUtility::makeInstance(ConfigurationManager::class);
        $extbaseFrameworkConfiguration = $configurationManager->getConfiguration(
            ConfigurationManagerInterface::CONFIGURATION_TYPE_FULL_TYPOSCRIPT
        )['plugin.']['tx_igreservations.'];
        $settings = $extbaseFrameworkConfiguration['settings.'];

        // set storagePids etc. for Query/Repository
        $configurationManager->setConfiguration($extbaseFrameworkConfiguration);

        // set environment to frontendMode for uri builder
        $environmentService = GeneralUtility::makeInstance(EnvironmentService::class);
        $environmentService->setFrontendMode(true);
        
        // set TYPO3_REQUEST for link builder from site with adminPageUid
        $finder = GeneralUtility::makeInstance(SiteFinder::class);
        $site = $finder->getSiteByPageId((int)$settings['adminPageUid']);
        $siteUrl = (string) $site->getBase();
        $request = (new ServerRequestFactory())->createServerRequest('GET', $siteUrl);
        $GLOBALS['TYPO3_REQUEST'] = $request->withAttribute('site', $site);



        $events = $this->eventRepository->findForAlarm('-1 week');

        if ($events->count() > 0) {
            $io->writeln('<comment>Found ' . $events->count() . ' events');
            $subject = 'Unbestätigte Buchungen';
            $from = $settings['coordinationPersonMailFrom'];
            $mailsTo = [$settings['coordinationPersonMailFrom']];

            $mailService = GeneralUtility::makeInstance(MailService::class);
            $mailService->setSettings($settings);
            $mailService->setRequest($GLOBALS['TYPO3_REQUEST']);
            $mailService->sendMail(
                $from,
                $mailsTo,
                $subject,
                'IgReservations/Command/Alarm/Admin',
                [
                    'events' => $events,
                    'settings' => $settings,
                ]
            );
        }

        return 0;
    }
}
