<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers\Form;

/**
 * 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
    {

      //$GLOBALS['TSFE'] -> additionalHeaderData['ig_datapool_fe_jqueryui'] = '<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />';
        //$GLOBALS['TSFE'] -> additionalFooterData['ig_datapool_fe_jqueryui'] = '<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script><script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/i18n/jquery-ui-i18n.min.js" ></script>';

        //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($this -> arguments['dateFormat']) . '" />';
        }
        $lang = \Internetgalerie\IgDatapoolFe\Utility\NeedfulThings::getCurLang('de');
        $res .= '<script>
        /*<![CDATA[*/
        jQuery.datepicker.regional["' . $lang . '"]["dateFormat"] = "' . strtolower($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(\TYPO3\CMS\Extbase\Property\TypeConverter\DateTimeConverter::class);
            $value = $converter -> convertFrom($value, 'DateTime', array(), null);
        }

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