<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers\Form;

use TYPO3\CMS\Fluid\ViewHelpers\Form\AbstractFormFieldViewHelper;
use TYPO3\CMS\Extbase\Security\Cryptography\HashService;
use TYPO3\CMS\Extbase\DomainObject\AbstractEntity;
use Internetgalerie\IgDatapoolFe\Services\IconService;

class InlinefieldViewHelper extends AbstractFormFieldViewHelper implements FieldInterface
{
    //Alias getValueAttribute From Trait!
    //use FieldTrait;
    /**
     * @var HashService
     */
    protected $hashService;

    /**
     * @param HashService $hashService
     */
    public function injectHashService(HashService $hashService): void
    {
        $this->hashService = $hashService;
    }
    public function initializeArguments(): void
    {
        parent::initializeArguments();
        $this->registerArgument('linePanelPosition', 'string', 'Position des Lösch-Knopfes', false, 'inline');
    }
    public function render(): string
    {
    //$name = $this->getName();
        //$this->registerFieldNameForFormTokenGeneration($name);

        $templateVariableContainer = $this->renderingContext->getVariableProvider();
        $output = '';
        $hiddenFields = '';
        // Loop through all  elements
        $origObjs = $this->getValueAttribute();


        $linePanelPosition =  $this->arguments['linePanelPosition'] ?? 'inline';
        
        //FIX IT, i.e. standardize it!!!
        $objects = [];
        $i = 0;
        // soolte ObjectStorage sein
        if (is_array($origObjs) || is_object($origObjs)) {
            foreach ($origObjs as $key => $obj) {
                if (is_numeric($key)) {
                    $objects[$key] = $obj;
                } else {
                    $objects[$i++] = $obj;
                }
            }
        }

        $count = 0;
        if (!empty($objects)) {
            $count = count($objects);
            foreach ($objects as $i => $obj) {
                //remove fields that actuelly arent
                if (!(is_array($obj) || $obj instanceof AbstractEntity)) {
                    continue;
                }
                //add variables to be used in fluid
                $templateVariableContainer->add('iterator', $i);
                $templateVariableContainer->add('prefix', $this->arguments['property'] . '.' . $i);

                //add a disabled hidden fields, which willb e enabled when the record is deleted, so the property mapper will delete the actual model
                //    $hiddenFields .= '<input class="record' . $i . '" type="hidden" name="' . $this->getName() . '[' . $i . ']" disabled="disabled" value="" />';

                // HTML output
                $output .= '
<div class="dp-record-container dp-record-container-persist" data-rel="' . trim(str_replace(['][', '['], '-', $this->getNameWithoutPrefix()), '[]') . '-' . $i . '">
<div class="dp-record">'
                        . $this->renderChildren()
                        . ($linePanelPosition != 'bottom' ? $this->renderLinePanel() : '')
                        . '</div>'
                        . ($linePanelPosition == 'bottom' ? $this->renderLinePanel() : '')
                        . '</div>';
                //remove them, to clean up
                $templateVariableContainer->remove('prefix');
                $templateVariableContainer->remove('iterator');
            }
        }
        //add the dummy element
        $output .= '
<div class="dp-record-container dp-record-container-dummy">
	<div class="dp-record">'
                . $this->renderDummyLine()
                . ($linePanelPosition != 'bottom' ? $this->renderLinePanel(false) : '')
                . '</div>'
                . ($linePanelPosition == 'bottom' ? $this->renderLinePanel(false) : '')
                . '</div>';
        //' . \Internetgalerie\IgDatapoolFe\Services\IconService::getIcon('actions-edit-delete', 'dp-delete', 'display:none') . '

        // add hidden fields
        // register for automapping @see ActionController
        $hiddenFields .= '<input type="hidden" name="' . $this->prefixFieldName('__dpInlineFields[]') . '" value="' . $this->hashService->appendHmac($this->arguments['property']) . '" />';
        //add an empty field, so a value is always submitted. also in the empty case.
        $hiddenFields .= '<input class="isEmpty" type="hidden" ' . ($count > 0 && 0 ? 'disabled="disabled"' : '') . ' name="' . htmlspecialchars($this->getName()) . '" value="" />';

        //last but not least, we need to reset the field, cause inner fields have been rendered!
        //\Internetgalerie\IgDatapoolFe\ViewHelpers\FieldWrapperViewHelper::setField($this);

        //return the context
        return '<div class="dp-form-inline dp-form-inline-field">
<div class="hiddenfields">' . $hiddenFields . '</div>
' . $output . '
</div>';
    }

    /**
     * @param bool $displayButtons
     *
     * @return string
     */
    public function renderLinePanel(bool $displayButtons = true)
    {
        $output = '<div class="dp-panel">';
        //$output = '<div class="dp-panel-inner"' . ($displayButtons ? '' :' style="display: none;"') . '>';
        $output .= IconService::getIcon('actions-edit-delete', 'dp-delete', $displayButtons ? '' : 'display:none');
        //$output .= '</div>';
        $output .= '</div>';
        return $output;
    }
    /**
     * Renders a dummy line for new values
     */
    protected function renderDummyLine()
    {
        $templateVariableContainer = $this->renderingContext->getVariableProvider();
        $output = '';
        $templateVariableContainer->add('prefix', $this->arguments['property'] . '.' . 'TEMP');

        $output .= $this->renderChildren();

        $templateVariableContainer->remove('prefix');

        //yep, this is ugly: set the fieldnames to dummies values
        $output = str_replace('name="', 'name="dummy-', $output);

        return $output;
    }
}
