<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers\Form;

use Internetgalerie\IgCoreViewhelpers\ViewHelpers\Form\HiddenViewHelper;

class ListBoxViewHelper extends 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);
    }

    /**
     * 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 = '';
        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((string) $value) . '" ';
            if ($this->arguments['filter']) {
                $data .= ' data-filter="' . $this->arguments['filter'] . '"';
            }

            if ($selected) {
                $class = ' selected';
                $this->tag->addAttribute('value', $value);
            } else {
                $class = '';
                $this->tag->addAttribute('value', '');
            }
            //$class .= ' item-id-' . $value;
            if ($this->arguments['as']) {
                $this->templateVariableContainer->add($this->arguments['as'], $option);
                $this->templateVariableContainer->add('selected', $selected);
            }
            $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;
        }
        $this->templateVariableContainer->remove($this->arguments['as']);
        return $output;
    }

    public function getDataValue($data, $field)
    {
        $fields = explode('.', (string) $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((string) $value) . '"';
                }
            }
        }
        return implode(' ', $data);
    }
}
