<?php

namespace Uhura\Grossmarkt\Domain\Finishers;

use In2code\Instagram\Domain\Repository\FeedRepository;
use TYPO3\CMS\Core\Database\Connection;
use TYPO3\CMS\Core\Database\ConnectionPool;
use TYPO3\CMS\Core\Mail\FluidEmail;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Fluid\View\TemplatePaths;
use TYPO3\CMS\Form\Domain\Finishers\Exception\FinisherException;
use TYPO3\CMS\Form\Domain\Runtime\FormRuntime;
use TYPO3\CMS\Form\ViewHelpers\RenderRenderableViewHelper;

class EmailFinisher extends \TYPO3\CMS\Form\Domain\Finishers\EmailFinisher
{
	protected function initializeFluidEmail(FormRuntime $formRuntime): FluidEmail
	{
		$templateConfiguration = $GLOBALS['TYPO3_CONF_VARS']['MAIL'];

		if (is_array($this->options['templateRootPaths'] ?? null)) {
			$templateConfiguration['templateRootPaths'] = array_replace_recursive(
				$templateConfiguration['templateRootPaths'],
				$this->options['templateRootPaths']
			);
			ksort($templateConfiguration['templateRootPaths']);
		}

		if (is_array($this->options['partialRootPaths'] ?? null)) {
			$templateConfiguration['partialRootPaths'] = array_replace_recursive(
				$templateConfiguration['partialRootPaths'],
				$this->options['partialRootPaths']
			);
			ksort($templateConfiguration['partialRootPaths']);
		}

		if (is_array($this->options['layoutRootPaths'] ?? null)) {
			$templateConfiguration['layoutRootPaths'] = array_replace_recursive(
				$templateConfiguration['layoutRootPaths'],
				$this->options['layoutRootPaths']
			);
			ksort($templateConfiguration['layoutRootPaths']);
		}

		$fluidEmail = GeneralUtility::makeInstance(
			FluidEmail::class,
			GeneralUtility::makeInstance(TemplatePaths::class, $templateConfiguration)
		);

		if (!isset($this->options['templateName']) || $this->options['templateName'] === '') {
			throw new FinisherException('The option "templateName" must be set to use FluidEmail.', 1599834020);
		}

		// Migrate old template name to default FluidEmail name
		if ($this->options['templateName'] === '{@format}.html') {
			$this->options['templateName'] = 'Default';
		}

		$feedSettings = [];
		$feedArray = [];

		if(isset($this->options['renderInstagramFeed'])){
			$queryBuilder = GeneralUtility::makeInstance(ConnectionPool::class)->getQueryBuilderForTable('tt_content');

			$flexForm = $queryBuilder->select('pi_flexform')
				->from('tt_content')
				->where(
					$queryBuilder->expr()->eq('list_type', $queryBuilder->createNamedParameter('instagram_pi1', Connection::PARAM_STR))
				)->executeQuery()->fetchOne();
			$flexForm = GeneralUtility::xml2arrayProcess($flexForm);
			if(isset($flexForm['data']['main']['lDEF']['settings.username']['vDEF'])){
				$userName = $flexForm['data']['main']['lDEF']['settings.username']['vDEF'];
				$feedRepository = GeneralUtility::getContainer()->get(FeedRepository::class);
				$feed = $feedRepository->findDataByUsername((string)$userName);
				$feedIndex = 0;
				$feedIndexKey = 1;

				foreach ($feed['data'] as $feedItem) {
					if(($feedIndex % 3) != 0){
						$feedArray[$feedIndexKey][] = $feedItem;
					} else {
						$feedIndexKey++;
						$feedArray[$feedIndexKey][] = $feedItem;
					}
					$feedIndex++;
				}
				foreach ($flexForm['data']['main']['lDEF']  as $key => $value) {
					$feedSettings[str_replace('settings.', '', $key)] = $value['vDEF'];
				}
			}
		}

		$fluidEmail
			->setRequest($this->finisherContext->getRequest())
			->setTemplate($this->options['templateName'])
			->assignMultiple([
				'finisherVariableProvider' => $this->finisherContext->getFinisherVariableProvider(),
				'form' => $formRuntime,
				'feeds' => $feedArray,
				'feedSettings' => $feedSettings,
			]);

		if (is_array($this->options['variables'] ?? null)) {
			$fluidEmail->assignMultiple($this->options['variables']);
		}

		$fluidEmail
			->getViewHelperVariableContainer()
			->addOrUpdate(RenderRenderableViewHelper::class, 'formRuntime', $formRuntime);
		return $fluidEmail;
	}
}