<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers\Form;

use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Property\TypeConverter\DateTimeConverter;
use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;
use TYPO3Fluid\Fluid\Core\Rendering\RenderingContextInterface;

class DateViewHelper extends TextfieldViewHelper
{

    static $settings = null;
    public function initSettings() {
        if (static::$settings === null) {
            $all = $this->configurationManager->getConfiguration(
                ConfigurationManagerInterface::CONFIGURATION_TYPE_FULL_TYPOSCRIPT
            );
            //tx_igdatapoolfe.
            static::$settings = $all['plugin.']['ig_datapool_fe.']['settings.'];
        }
        return static::$settings;
    }

    
    public function initializeArguments(): void
    {
        parent::initializeArguments();

        $this->registerArgument('plugin', 'string', 'Minimum Datum', false);

        // default (browser)
        //$this->overrideArgument('class', 'string', 'class', false, 'dp-date dp-input-date');
        $this->registerTagAttribute('min', 'string', 'Minimum Datum', false);
        $this->registerTagAttribute('max', 'string', 'Maximum Datum', false);

        // pickadate
        $this->registerArgument('minDate', 'string', 'Minimum Datum', false);
        $this->registerArgument('maxDate', 'string', 'Maximum Datum', false);
        $this->registerArgument('dateFormat', 'string', 'Format for output', false, 'dd.mm.yyyy');
        $this->registerArgument('formatSubmit', 'string', 'Format Submit', false, 'yyyy-mm-dd');
        $this->registerArgument('typeConverterDateFormat', 'string', 'date format for DateTimeConverter (field dateFormat)', false);
        $this->registerArgument('hiddenName', 'bool', 'hiddenName', false, true);
        $this->registerArgument('selectYears', 'int', 'Jahrespulldown darstellen', false, false);
        $this->registerArgument('selectMonths', 'bool', 'Monatspulldown darstellen', false, false);
        $this->registerArgument('datepickerOptions', 'string', 'Format', false, '');
        //$this->registerArgument('language', 'string', 'Sprache für JS translations File', false);// geht nur letzte auf Seite
        $this->overrideArgument('placeholder', 'string', 'Label', false, 'dd.mm.yyyy');
        $this->registerArgument('submitOnChange', 'boolean', '', false);
        $this->registerArgument('showToday', 'bool', 'Show today button', false, true);
        $this->registerArgument('showClear', 'bool', 'Show clear button', false, true);
        $this->registerArgument('showClose', 'bool', 'Show close button', false, true);
        /*
          $settings = $this->initSettings();
          if ($settings['pickadate.']['enable'] ?? false) {
            $this->overrideArgument('class', 'string', 'Label', false, 'dp-date dp-pickadate');
          } else {
            $this->overrideArgument('type', 'string', 'The field type, e.g. "text", "email", "url" etc.', false, 'date');
          }
        */
    }

    public function render(): string
    {
        $settings = $this->initSettings();
        $pickadateEnable = $settings['pickadate.']['enable'] ?? false;
        $plugin = $this->arguments['plugin'] ?? '';

        if ($pickadateEnable && ($plugin == '' || $plugin == 'pickadate')) {
            return $this->renderPickadate();
        }

        if (!$this->hasArgument('class')) {
            $this->arguments['class'] = 'dp-date dp-input-date';
            $this->tag->addAttribute('class', $this->arguments['class']);
        }
        $this->arguments['type'] = 'date';
        return parent::render();
    }

    public function renderPickadate(): string
    {
        $pageRenderer = GeneralUtility::makeInstance(\TYPO3\CMS\Core\Page\PageRenderer::class);

        $options = [];
        $options['format']= strtolower($this->arguments['dateFormat']);
        $options['formatSubmit'] =  $this->arguments['formatSubmit'];
        $options['hiddenName'] = ($this->arguments['hiddenName'] ? true : false);

        if (!$this->hasArgument('class')) {
            $this->arguments['class'] = 'dp-date dp-pickadate';
            $this->tag->addAttribute('class', $this->arguments['class']);
        }

        if ($this->arguments['selectYears']) {
            if ((int)$this->arguments['selectYears'] >1) {
                $options['selectYears'] =(int)$this->arguments['selectYears'];
            } else {
                $options['selectYears'] = $this->arguments['selectYears'] ? true : false;
            }
        }
        if ($this->arguments['selectMonths']) {
            $options['selectMonths'] = true;
        }
        if ($this->arguments['minDate']) {
            $date = explode('-', $this->arguments['minDate']);
            $options['min'] = [ intval($date[0]) , intval($date[1]-1) , intval($date[2]) ];
        }
        if ($this->arguments['maxDate']) {
            $date = explode('-', $this->arguments['maxDate']);
            $options['max'] = [ intval($date[0]) , intval($date[1]-1) , intval($date[2]) ];
        }
        $submitOnChange = $this->arguments['submitOnChange'] ?? '';
        $showToday = $this->arguments['showToday'];
        $showClear = $this->arguments['showClear'];
        $showClose = $this->arguments['showClose'];
        //	"formatSubmit" : "dd.mm.yyyy",
        if (!$showToday) {
            $options['today'] = null;
        }
        if (!$showClear) {
            $options['clear'] = null;
        }
        if (!$showClose) {
            $options['close'] = null;
        }

        if ($this->arguments['datepickerOptions']) {
            if (is_array($this->arguments['datepickerOptions'])) {
                $options = array_merge($options, $this->arguments['datepickerOptions']);
            } else {
                // support older string format
                $datepickerOptions = json_decode('{' . str_replace('\'', '"', $this->arguments['datepickerOptions']) .'}', true);
                $options = array_merge($options, $datepickerOptions);
            }
        }

        //$options = '{' .  $datepickerOptions;
        //$options = rtrim(rtrim($options), ',') . '}';

        $value = $this->getValueAttribute();

        if ($this->isObjectAccessorMode()) {
            $value = $this->getPropertyValue();
        }

        //$value = $this->convertToPlainValue($value);
        // is property Value
        if ($value instanceof \DateTime) {
            $typeConverterDateFormat = $this->getTypeConverterFormatSubmit();
            $value = $value->format($typeConverterDateFormat);
            //$value = $value->format('Y-m-d');
        }

        $this->tag->addAttribute('data-dateoptions', json_encode($options));
        $this->tag->addAttribute('data-value', $value);
        if ($submitOnChange) {
            $this->tag->addAttribute('data-submit', $submitOnChange);
        }

        $res = parent::render();

        // CAVEAT: this has to match the formatSubmit (format in js: yyyy-mm-dd, format in php Y-m-d)
        $typeConverterDateFormat = $this->getTypeConverterFormatSubmit();
        $res .= '<input type="hidden" name="' . parent::getName() . '[dateFormat]" value="' . htmlspecialchars($typeConverterDateFormat) . '" />';
        return $res;

    }


    
    protected function getName(): string
    {
        return parent::getName() . '[date]';
        //return parent::getName() . ($this->arguments['hiddenName']!==true ? '[date]' : '');
    }

    /**
     * Get the value of this form element.
     * Either returns arguments['value'], or the correct value for Object Access.
     *
     * @param  boolean $convertObjects whether or not to convert objects to identifiers
     * @return mixed Value
     */
    protected function getValueAttribute($convertObjects = true)
    {
        $value = parent::getValueAttribute();
        if (is_array($value)) {
            $converter = GeneralUtility::makeInstance(DateTimeConverter::class);
            // set default dateformat if nothing is set
            if (isset($value['date']) && (!isset($value['dateFormat']) || $value['dateFormat'] === '')) {
                $value['dateFormat'] = $this->getTypeConverterFormatSubmit();
            }
            $value = $converter->convertFrom($value, 'DateTime', [], null);
        }

        if (is_a($value, \DateTime::class)) {
            //$typeConverterDateFormat = $this->getTypeConverterDateFormat();
            $typeConverterDateFormat = $this->getTypeConverterFormatSubmit();
            return $value->format($typeConverterDateFormat);
        }
        return $value;
    }

    /**
     * Format date for
     */
    protected function getTypeConverterFormatSubmit()
    {
        if (isset($this->arguments['typeConverterDateFormat'])) {
            return $this->arguments['typeConverterDateFormat'];
        }
        $typeConverterDateFormat = $this->arguments['formatSubmit'];
        $typeConverterDateFormat = str_replace('yyyy', 'Y', $typeConverterDateFormat);
        return str_replace(['yy', 'mm', 'dd'], ['y', 'm', 'd'], $typeConverterDateFormat);
    }

    /**
     * Format date for output
     */
    protected function getTypeConverterDateFormat()
    {
        $typeConverterDateFormat = $this->arguments['dateFormat'];
        $typeConverterDateFormat=str_replace('yyyy', 'Y', $typeConverterDateFormat);
        return str_replace(['yy', 'mm', 'dd'], ['y', 'm', 'd'], $typeConverterDateFormat);
    }
}
