<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers\Form;

use TYPO3\CMS\Core\Utility\GeneralUtility;

class ListBoxViewHelper extends \Internetgalerie\IgCoreViewhelpers\ViewHelpers\Form\HiddenViewHelper
{
    protected $escapeOutput = false;
    /**
     * Initialize arguments.
     *
     * @return void
     * @api
     */
    public function initializeArguments(): void
    {
        parent::initializeArguments();
        $this->registerArgument('as', 'string', 'as', true, null);
        $this->registerArgument('options', 'array', 'options', true, null);
        $this->registerArgument('search', 'array', 'search', false, null);
        // this field which is compared to search
        $this->registerArgument('optionValueField', 'string', 'value field', false, 'uid');
        $this->registerArgument('filter', 'string', 'data-filter', false, null);
        $this->registerArgument('iteration', 'string', 'The name of the variable to store iteration information (index, cycle, isFirst, isLast, isEven, isOdd)');
        $this->registerArgument('vModel', 'string', 'v-model base name', false, null);
        $this->registerArgument('vClick', 'string', 'vue @click', false, null);
    }

    /**
     * Render the tag.
     *
     * @return string rendered tag.
     * @api
     */
    public function render(): string
    {
        $hiddenValue = '';
        $selected = false;
        $formName = $this->getName();
        $this->tag->addAttribute('type', 'hidden');
        $this->registerFieldNameForFormTokenGeneration($formName);
        $this->setRespectSubmittedDataValue(true);

        if (empty($this->arguments['options'])) {
            return '';
        }
        $output = '';
        if (isset($arguments['iteration'])) {
            $iterationData = [
                'index' => 0,
                'cycle' => 1,
                'total' => count($arguments['each'])
            ];
        }
        $index = 0;
        foreach ($this->arguments['options'] as $option) {
            $selected = $this->getSelected($option);
            $data = $this->getDataAttribute($option);
            $value = $this->getDataValue($option, $this->arguments['optionValueField']);
            $dataValue = ' data-val="' . htmlspecialchars($value) . '" ';
            $dataValue .= ' data-group="' . htmlspecialchars($this->arguments['name']) . '" ';
            if ($this->arguments['filter']) {
                $data .= ' data-filter="' . $this->arguments['filter'] . '"';
            }
            $data .= ' data-index=' . $index . '"';
            if ($selected) {
                $class = ' selected';
                $this->tag->addAttribute('value', $value);
            } else {
                $class = '';
                $this->tag->addAttribute('value', '');
            }
            if ($this->arguments['vModel']) {
                $this->tag->addAttribute('v-model', $this->arguments['vModel'].'[' . $index . ']');
            }
            if ($this->arguments['vClick']) {
                $data .= ' @click="' . $this->arguments['vClick'] . '"';
            }
            
            //$class .= ' item-id-' . $value;
            if ($this->arguments['as']) {
                $this->templateVariableContainer->add($this->arguments['as'], $option);
                $this->templateVariableContainer->add('selected', $selected);
            }
            if (isset($arguments['iteration'])) {
                $iterationData['isFirst'] = $iterationData['cycle'] === 1;
                $iterationData['isLast'] = $iterationData['cycle'] === $iterationData['total'];
                $iterationData['isEven'] = $iterationData['cycle'] % 2 === 0;
                $iterationData['isOdd'] = !$iterationData['isEven'];
                $templateVariableContainer->add($arguments['iteration'], $iterationData);
                $iterationData['index']++;
                $iterationData['cycle']++;
            }


            $name = $formName . '[]';
            $this->tag->addAttribute('name', $name);

            $before = '<div class="dp-item item' . $class . '"' . $dataValue . $data . '>';

            $after = '</div>';
            $output .= $before . $this->tag->render() . $this->renderChildren() . $after;
            if (isset($arguments['iteration'])) {
                $templateVariableContainer->remove($arguments['iteration']);
            }
            if ($this->arguments['as']) {
                $this->templateVariableContainer->remove($this->arguments['as']);
                $this->templateVariableContainer->remove('selected');
                $index++;
            }
        }
        return $output;
    }

    public function getDataValue($data, $field)
    {
        $fields = explode('.', $field);

        foreach ($fields as $field) {
            if (is_object($data)) {
                //$dataValueFieldGetter = 'get' . ucfirst($field);
                $data = $data->{'get' . ucfirst($field)}();
            } elseif ($data !== null && is_array($data)) {
                $data = $data[$field] ?? null;
            } else {
                return null;
            }
        }
        return $data;
    }
    /*
    public function getValueFieldGetter($optionValueField)
    {
        return 'get' . ucfirst($optionValueField);
    }
    */
    public function getSelected($option)
    {
        $selected = false;
        if ($this->arguments['search']) {
            $searchForm = $this->arguments['search'];
            $optionValue = $this->getDataValue($option, $this->arguments['optionValueField']);

            //if (is_array($option)) {
            foreach ($searchForm as $searchItem) {
                //if ($option->getId() == trim($search)) {
                if ($optionValue == $searchItem) {
                    $selected = true;
                }
            }
        }
        return $selected;
    }
    public function getDataAttribute($option)
    {
        $data = [];
        if ($this->arguments['data']) {
            foreach ($this->arguments['data'] as $key => $field) {
                //$newGetter = 'get' . ucfirst($value);
                $value =  $this->getDataValue($option, $field);
                if (!$value) {
                    $value =  $this->getDataValue($option, 'value');
                }
                //var_dump($this->arguments['data'], $option, $field, $value);exit(0);
                if ($value) {
                    $data[] = 'data-' . $key . '="' . htmlspecialchars($value) . '"';
                }
            }
        }
        return implode(' ', $data);
    }
}
