<?php

namespace Uhura\Grossmarkt\Domain\Finishers;


use TYPO3\CMS\Core\Http\ImmediateResponseException;
use TYPO3\CMS\Core\Http\JsonResponse;
use TYPO3\CMS\Core\Utility\ArrayUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Fluid\View\StandaloneView;
use TYPO3\CMS\Form\Domain\Finishers\AbstractFinisher;
use TYPO3\CMS\Form\Domain\Finishers\Exception\FinisherException;
use TYPO3\CMS\Form\Domain\Runtime\FormRuntime;
use TYPO3\CMS\Form\ViewHelpers\RenderRenderableViewHelper;

class SuccessFinisher extends AbstractFinisher
{
	/**
	 * @return string|void|null
	 * @throws \TYPO3\CMS\Extbase\Persistence\Exception\IllegalObjectTypeException
	 */
	protected function executeInternal()
	{
		$formValues = $this->finisherContext->getFormValues();
		$formValues = ArrayUtility::removeNullValuesRecursive($formValues);

		$formRuntime = $this->finisherContext->getFormRuntime();
		$settings = $formRuntime->getFormDefinition()->getRenderingOptions();
		$confirmationText = isset($settings['confirmationText']) ? $settings['confirmationText'] : false;

		$standaloneView = $this->initializeStandaloneView(
			$this->finisherContext->getFormRuntime()
		);
		$standaloneView->assignMultiple([
			'confirmationText' => $confirmationText,
			'formValues' => $formValues,
		]);

		if(isset($formValues['jsonResponse'])){
			$responseData = [
				'isSuccess' => true,
			];
			$response = GeneralUtility::makeInstance(JsonResponse::class, $responseData);
			throw new ImmediateResponseException($response);
		}

		return $standaloneView->render();
	}


	/**
	 * @param FormRuntime $formRuntime
	 * @return StandaloneView
	 * @throws FinisherException
	 */
	protected function initializeStandaloneView(FormRuntime $formRuntime): StandaloneView
	{
		$standaloneView = GeneralUtility::getContainer()->get(StandaloneView::class);

		if (!isset($this->options['templateName'])) {
			throw new FinisherException(
				'The option "templateName" must be set for the ConfirmationFinisher.',
				1521573955
			);
		}

		$standaloneView->setTemplate($this->options['templateName']);
		$standaloneView->getTemplatePaths()->fillFromConfigurationArray($this->options);

		if (isset($this->options['variables']) && is_array($this->options['variables'])) {
			$standaloneView->assignMultiple($this->options['variables']);
		}

		$standaloneView->assign('form', $formRuntime);
		$standaloneView->assign('finisherVariableProvider', $this->finisherContext->getFinisherVariableProvider());

		$standaloneView->getRenderingContext()
			->getViewHelperVariableContainer()
			->addOrUpdate(RenderRenderableViewHelper::class, 'formRuntime', $formRuntime);

		return $standaloneView;
	}
}