<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers\Form;

use Internetgalerie\IgDatapoolFe\ViewHelpers\FormViewHelper;
use Internetgalerie\IgDatapoolFe\Utility\NeedfulThings;

/**
 * Validation results view helper
 *
 * @api
 * @author     Markus Baumgartner <mb@stylesheep.ch>, Internetgalerie AG
 * @package    IgDatapoolFE
 * @subpackage ViewHelpers
 */
class ValidationResultsViewHelper extends \Internetgalerie\IgCoreViewhelpers\ViewHelpers\Form\ValidationResultsViewHelper
{
    public function initializeArguments(): void
    {
        parent::initializeArguments();
    }


    /**
     * Iterates through selected errors of the request.
     *
     * @return string Rendered string
     * @api
     */
    public function render(): string
    {
        if (($res = trim(parent::render($this->arguments['for'], $this->arguments['as']))) != '') {
            return $res;
        }
        //$validationResults = $this->renderingContext->getRequest()->getOriginalRequestMappingResults()->forProperty($for)->getFlattenedErrors();
        $for = $this->arguments['for'];
        $validationResults = $this->renderingContext->getRequest()->getAttribute('extbase')->getOriginalRequestMappingResults()->forProperty($for)->getFlattenedErrors();
        if (!$validationResults) {
            return '';
        }
        $out = '<ul class="dp-errorBox">';

        foreach ($validationResults as $field => $result) {
            $label = \Internetgalerie\IgDatapoolFe\Utility\NeedfulThings::getFieldLabelByProperty($field);

            foreach ($result as $error) {
                $out .= '<li>' . ($label != '' ? (htmlspecialchars($label) . ': ') : '') . htmlspecialchars($error->render()) . '</li>';
            }
        }
        $out .= '</ul>';
        return $out;
    }
}
