<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers\Form;

use Internetgalerie\IgCoreViewhelpers\ViewHelpers\Form\HiddenViewHelper;
use TYPO3\CMS\Core\Utility\GeneralUtility;

/**
 * Renders all values of an array as <input type="hidden" ...> tag.
 *
 */
class HiddenArrayViewHelper extends HiddenViewHelper implements FieldInterface
{
    /**
     * Initialize arguments.
     *
     * @return void
     * @api
     */
    public function initializeArguments(): void
    {
        parent::initializeArguments();
        $this->overrideArgument('value', 'array', 'array to render in hidden', false);
        $this->registerArgument('exclude', 'string', 'exclude names', false);
        $this->registerArgument('noInternal', 'bool', 'array to render in hidden', false, false);
    }

    private function renderArray(string $formName, array $array)
    {
        $html = '';
        foreach ($array as $name => $value) {
            $name = $formName . '[' . $name . ']';
            if (is_array($value)) {
                if (!empty($value)) {
                    $html .= $this->renderArray($name, $value);
                }
            } else {
                $this->tag->addAttribute('name', $name);
                $this->tag->addAttribute('value', $value);
                $this->registerFieldNameForFormTokenGeneration($name);
                $html .=  $this->tag->render();
                //$html .= '<input type="hidden" name="' . $name . '" value="' . $value .'" />';
            }
        }
        return $html;
    }

    /**
     * Render the tag.
     *
     * @return string rendered tag.
     * @api
     */
    public function render(): string
    {
        $value = $this->arguments['value'] ?? [];
        if (isset($this->arguments['exclude'])) {
            $exclude = GeneralUtility::trimExplode(',', $this->arguments['exclude'], true);
            foreach ($exclude as $key) {
                if (isset($value[$key])) {
                    unset($value[$key]);
                }
            }
        }
        $html = '';
        if (!empty($value)) {
            $name = $this->getName();
            $this->tag->addAttribute('type', 'hidden');
            $this->setRespectSubmittedDataValue(true);
            $html .= $this->renderArray($name, $value);
        }
        return $html;
    }
}
