<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers\Form;

use Internetgalerie\IgDatapoolFe\Utility\NeedfulThings;
use TYPO3\CMS\Extbase\Property\TypeConverter\DateTimeConverter;

/**
 * View Helper which creates a text field (<input type="text">).
 *
 * = Examples =
 *
 * <code title="Example">
 * <f:form.textfield name="myTextBox" value="default value" />
 * </code>
 * <output>
 * <input type="text" name="myTextBox" value="default value" />
 * </output>
 *
 * @api
 * @author     Markus Baumgartner <mb@stylesheep.ch>, Internetgalerie AG
 * @package    IgDatapoolFE
 * @subpackage ViewHelpers
 */
class OldDateViewHelper extends TextfieldViewHelper implements FieldInterface
{
    //Alias getValueAttribute From Trait!
    use FieldTrait {
    FieldTrait::getValueAttribute as traitGetValue;
}

    public function initializeArguments(): void
    {
        parent::initializeArguments();
        $this -> registerArgument('dateFormat', 'string', 'Format', false, 'd.m.Y');
        $this -> registerArgument('dateFormatJQueryUi', 'string', 'Format', false, 'dd.mm.yy');
        $this -> registerArgument('datepickerOptions', 'string', 'Format', false, '');
        $this -> overrideArgument('class', 'string', 'Label', false, 'datepicker');
        $this -> overrideArgument('placeholder', 'string', 'Label', false, 'dd.mm.yyyy');
    }

    /**
     * Renders the textfield.
     *
     * @return string
     * @api
     */
    public function render(): string
    {
        //Automagically set required
        $required = $this->arguments['required'] ?? $this->isRequiredByAnnotation();

        /**
         * TYPO3 fluid Bug workaround
         * The fluid viewhelper only checks for NULL isntead of evaluating the boolean
         */
        if ($required === false) {
            $required = null;
        }

        $res = parent::render($required, 'text');
        if ($this -> hasArgument('dateFormat')) {
            $res .= '<input type="hidden" name="' . parent::getName() . '[dateFormat]" value="' . htmlspecialchars((string) $this -> arguments['dateFormat']) . '" />';
        }
        $lang = NeedfulThings::getCurLang($this->getRequest(), 'de');
        $res .= '<script>
        /*<![CDATA[*/
        jQuery.datepicker.regional["' . $lang . '"]["dateFormat"] = "' . strtolower((string) $this -> arguments['dateFormatJQueryUi']) . '";
        jQuery.datepicker.setDefaults(jQuery.datepicker.regional["' . $lang . '"]);
        jQuery(document).ready(
            function () {
                jQuery("#' . $this -> getId() . '").datepicker(
                    {
                    showOn : "both",
                    buttonImage: "/typo3conf/ext/ig_datapool_fe/Resources/Public/Icons/calendar.png",
                    buttonImageOnly: true,
                    autoSize: true,
                    ' . $this -> arguments['datepickerOptions'] . '
                    }
                );
            }
        );
        /*]]>*/
        </script>';
        return $res;
    }

    protected function getName(): string
    {
        return parent::getName() . '[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 = $this -> traitGetValue($convertObjects);

        if (is_array($value)) {
            $converter = GeneralUtility::makeInstance(DateTimeConverter::class);
            $value = $converter -> convertFrom($value, 'DateTime', [], null);
        }

        if (is_a($value, '\DateTime')) {
            return $value -> format($this -> hasArgument('dateFormat') ? $this -> arguments['dateFormat'] : 'd.m.Y');
        }
        return $value;
    }
}
