<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers\Form;

use DateTime;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Page\PageRenderer;

class EasepickViewHelper extends AbstractDatetimeViewHelper
{

    // remove if v12 is dropped
    protected PageRenderer $pageRenderer;

    public function injectPageRenderer(PageRenderer $pageRenderer): void
    {
        $this->pageRenderer = $pageRenderer;
    }

    public function initializeArguments(): void
    {
        parent::initializeArguments();
        $this->registerArgument('dateFormat', 'string', 'Format for output', false, 'DD.MM.YYYY');
        $this->registerArgument('formatSubmit', 'string', 'Format Submit', false, 'YYYY-MM-DD'); // Easepick does not support that
        $this->registerArgument('typeConverterDateFormat', 'string', 'date format for DateTimeConverter (field dateFormat)', false, 'Y');
        $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('minDate', 'string', 'Minimum Datum', false);
        $this->registerArgument('maxDate', 'string', 'Maximum Datum', 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('class', 'string', 'Label', false, 'dp-easepick');
        $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);
    }

    /**
     * Renders the datefield.
     *
     * @return string
     * @api
     */
    public function render(): string
    {
        $this->pageRenderer->loadJavaScriptModule('@dp/elements/easepickField.js');
        $options = [];
        $options['format']= ($this->arguments['dateFormat']);
        $options['formatSubmit'] =  $this->arguments['formatSubmit'];
        $options['hiddenName'] = ($this->arguments['hiddenName'] ? true : false);

        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['minDate'] = $this->arguments['minDate'];
        }
        if ($this->arguments['maxDate']) {
            //$date = explode('-', $this->arguments['maxDate']);
            $options['maxDate'] = $this->arguments['maxDate'];
        }
        $submitOnChange = $this->arguments['submitOnChange'] ?? '';
        $showToday = $this->arguments['showToday'];
        //	"formatSubmit" : "dd.mm.yyyy",
        if (!$showToday) {
            $options['today'] = 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->getTypeConverterDateFormat();
            $value = $value->format($typeConverterDateFormat);
            //$value = $value->format('Y-m-d');
        } else if(is_string($value) && $value !== '') {
            $dateTime = new DateTime($value);
            $typeConverterDateFormat = $this->getTypeConverterDateFormat();
            $value = $dateTime->format($typeConverterDateFormat);
        }

        $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();
        //$value = $this->getValueAttribute();        var_dump($value,$res);exit(0);

        // 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;
    }
}
