<?php
/**
 * @author Rafael Ostertag <rafael.ostertag@math.uzh.ch>
 */

namespace IMATHUZH\Qfq\Controller;

require_once(__DIR__ . '/../../vendor/autoload.php');

use IMATHUZH\Qfq\Core\QuickFormQuery;


/**
 * Class QfqController
 * @package IMATHUZH\Qfq\Controller
 */
class QfqController extends \TYPO3\CMS\Extbase\Mvc\Controller\ActionController {

    /**
     * @return string
     * @throws \CodeException
     * @throws \PhpOffice\PhpSpreadsheet\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Reader\Exception
     * @throws \PhpOffice\PhpSpreadsheet\Writer\Exception
     * @throws \Twig\Error\LoaderError
     * @throws \Twig\Error\RuntimeError
     * @throws \Twig\Error\SyntaxError
     * @throws \UserFormException
     */
    public function showAction() {

        $html = '';
        $origErrorReporting = '';
        $flagOk = false;

        try {
            $contentObject = $this->configurationManager->getContentObject();

            // By T3 default 'E_NOTICE' is unset. E.g. 'Undefined Index' will throw an exception.
            // QFQ like to see those 'E_NOTICE'
            $origErrorReporting = error_reporting();
            error_reporting($origErrorReporting | E_NOTICE);

            $qfq = new QuickFormQuery($contentObject->data);
            $html = $qfq->process();
            $flagOk = true;

        } catch (\UserFormException $e) {
            $html = $e->formatMessage();

        } catch (\UserReportException $e) {
            $html = $e->formatMessage();

        } catch (\CodeException $e) {
            $html = $e->formatMessage();

        } catch (\DbException $e) {
            $html = $e->formatMessage();

        } catch (\ShellException $e) {
            $html = $e->formatMessage();

        } catch (\DownloadException $e) {
            $html = $e->formatMessage();

        } catch (\Exception $e) {
            $ee = new \UserReportException(json_encode([
                ERROR_MESSAGE_TO_USER => "Generic Exception: " . $e->getMessage(),
                ERROR_MESSAGE_TO_DEVELOPER => $e->getTraceAsString()]), E_ERROR);
            $html = $ee->formatMessage();
        } catch (\Throwable $e) {
            $ee = new \UserReportException(json_encode([
                ERROR_MESSAGE_TO_USER => "Generic Error: " . $e->getMessage(),
                ERROR_MESSAGE_TO_DEVELOPER => $e->getTraceAsString()]), E_ERROR);
            $html = $ee->formatMessage();
        }

        if (isset($e) && $e->getCode() == ERROR_QUIT_QFQ_REGULAR) {
            $flagOk = true;
        }

        if (!$flagOk) {
            $html = "<div class='alert alert-warning'>$html</div>";
        }

        // Restore has to be outside of try/catch - E_NOTICE needs to unset for further T3 handling after an QFQ Exception.
        error_reporting($origErrorReporting);

        $this->view->assign('qfqOutput', $html);

        return $this->view->render();
    }

}