<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers\Form;

use TYPO3\CMS\Fluid\ViewHelpers\FormViewHelper;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;

/**
 * Display a field error
 *
 *         <dp:form.fieldError property="title" as="errorResult">Error<f:debug>{errorResult}</f:debug></dp:form.fieldError>
 *         <dp:form.fieldError property="title"><f:then>Error</f:then><f:else>OK</f:else></dp:form.fieldError>
 */
class ErrorByCodeViewHelper extends FieldErrorViewHelper
{
    /**
     * Initialize the arguments.
     *
     * @return void
     * @api
     */
    public function initializeArguments(): void
    {
        $this->registerArgument('code', 'int', 'code of error', true, '');
        $this->registerArgument('as', 'string', 'name for errorResult object', false, 'error');
    }

    public static function verdict(array $arguments, RenderingContextInterface $renderingContext)
    {
        $mappingResults = static::getMappingResultsForProperty($arguments, $renderingContext);
        return $mappingResults;
    }

    /**
     * Get errors for the property and form name of this ViewHelper
     */
    protected static function getMappingResultsForProperty(array $arguments, RenderingContextInterface $renderingContext)
    {
        $originalRequestMappingResults = $renderingContext->getRequest()->getAttribute('extbase')->getOriginalRequestMappingResults();

        $formObjectName = $renderingContext->getViewHelperVariableContainer()->get(
            FormViewHelper::class,
            'formObjectName'
        );
        $formErrors= $originalRequestMappingResults->forProperty($formObjectName);
        foreach ($formErrors->getErrors() as $error) {
            if ($error->getCode()==$arguments['code']) {
                return $error;
            }
        }
        return '';
    }
}
