<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers\Form;

use Internetgalerie\IgCoreViewhelpers\ViewHelpers\Form\TextareaViewHelper;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\PathUtility;
use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;
use TYPO3\CMS\Extbase\Property\TypeConverter\DateTimeConverter;

/**
 * Textarea view helper.
 * The value of the text area needs to be set via the "value" attribute, as with all other form ViewHelpers.
 *
 * = Examples =
 *
 * <code title="Example">
 * <f:form.textarea name="myTextArea" value="This is shown inside the textarea" />
 * </code>
 * <output>
 * <textarea name="myTextArea">This is shown inside the textarea</textarea>
 * </output>
 */
class HtmlViewHelper extends TextareaViewHelper
{
    /**
     * @var string Name of the extension this view helper belongs to
     */
    protected $extensionName = 'IgDatapoolFe';

    /**
     * @var string Name of the extension this view helper belongs to (ext_localconf.php configurePlugin zweites  Argument)
     */
    protected $pluginName = 'ig_datapool_fe';

    /**
     * Initialize the arguments.
     *
     * @return void
     * @api
     */
    public function initializeArguments(): void
    {
        parent::initializeArguments();
        //$this->registerArgument('plugins', 'string', 'plugins to load', false, '');
        $this->registerArgument('toolbarLine1', 'string', 'toolbar https://www.tinymce.com/docs/advanced/editor-control-identifiers/#toolbarcontrols', false, '');
        $this->registerArgument('toolbarLine2', 'string', 'toolbar https://www.tinymce.com/docs/advanced/editor-control-identifiers/#toolbarcontrols', false, '');
        $this->registerArgument('toolbarLine3', 'string', 'toolbar https://www.tinymce.com/docs/advanced/editor-control-identifiers/#toolbarcontrols', false, '');
        $this->registerArgument('toolbarLocation', 'string', 'toolbarLocation top, bottom', false);
        $this->registerArgument('config', 'string', 'configuration/style to use', false, "default");
    }



    /**
     * Renders the textarea.
     *
     * @return string
     * @api
     */
    public function render(): string
    {
        $this->settings = $this->configurationManager->getConfiguration(ConfigurationManagerInterface::CONFIGURATION_TYPE_FULL_TYPOSCRIPT);//, $this->extensionName);//, $this->pluginName);
        $rteSettings=$this->settings['plugin.']['ig_datapool_fe.']['rte.'];
        $fieldId = $this->arguments['id'] ? : 'dp-field-ckeditor-' . $this->arguments['property'] ?? str_replcae(['[', ']', '.'], '-', $this->getName());

        $toolbar=[];
        if ($this->arguments['toolbarLine1']) {
            $toolbar[]=json_decode('[' . str_replace("'", '"', $this->arguments['toolbarLine1']) . ']');
        }
        if ($this->arguments['toolbarLine2']) {
            $toolbar[]='/';
            $toolbar[]=json_decode('[' . str_replace("'", '"', $this->arguments['toolbarLine2']) . ']');
        }
        if ($this->arguments['toolbarLine3']) {
            $toolbar[]='/';
            $toolbar[]=json_decode('[' . str_replace("'", '"', $this->arguments['toolbarLine3']) . ']');
        }
        $lang = \Internetgalerie\IgDatapoolFe\Utility\NeedfulThings::getCurLang('de');
        $configuration = [
            'customConfig' => '',
            'stylesSet' => [],
        ];
        if (count($toolbar)) {
            $configuration['toolbar'] =  $toolbar;
        }

        if ($this->arguments['toolbarLocation']) {
            $configuration['toolbarLocation']=$this->arguments['toolbarLocation'];
        }

        if ($this->arguments['config'] && isset($rteSettings[$this->arguments['config']])) {
            $config=trim($rteSettings[$this->arguments['config']]);

            $jsonConfiguration= json_encode(json_decode($config)); // Funktioniert nur so, ohne decode und encode wills nicht gehen, liegt wohl an speziellen zeichen
        } else {
            $jsonConfiguration = json_encode($configuration);
        }

        $this->tag->addAttribute('id', $fieldId);

        // render hidden field for filter (e.x. remove empty lines, (remove \r and \n))
        $filterName = $this->getName() . '[__filter]';
        $this->registerFieldNameForFormTokenGeneration($filterName);
        $hiddenField = '<input type="hidden" name="' . $filterName . '" value="html" />';

        // render textarea
        $required = $this->arguments['required'] ?? false;
        $name = $this->getName() . '[html]';
        $this->registerFieldNameForFormTokenGeneration($name);
        $this->setRespectSubmittedDataValue(true);

        $this->tag->forceClosingTag(true);
        $this->tag->addAttribute('name', $name);
        if ($required === true) {
            $this->tag->addAttribute('required', 'required');
        }

        $value = $this->getValueAttribute();
        $this->tag->setContent(htmlspecialchars(is_array($value) ? $value['html'] : $value));
        $this->addAdditionalIdentityPropertiesIfNeeded();
        $this->setErrorClassAttribute();

        //$js = PathUtility::getPublicResourceWebPath('EXT:rte_ckeditor/Resources/Public/Contrib/ckeditor5-bundle.js');
        if (\TYPO3\CMS\Core\Utility\VersionNumberUtility::convertVersionNumberToInteger(\TYPO3\CMS\Core\Utility\VersionNumberUtility::getNumericTypo3Version()) >= 12000000) {
            $js = PathUtility::getPublicResourceWebPath('EXT:ig_datapool_fe/Resources/Public/Contrib/ckeditor.js');
            $GLOBALS['TSFE']->additionalFooterData['ig_datapool_fe_rte'] = '<script src="' . $js . '" data-ignore="1"></script>';
        }
        return '<div class="dp-ckeditor dp-ckeditor-' . $this->arguments['config'] . '" data-language="' . $lang . '" data-config="' . htmlspecialchars($jsonConfiguration) . '">' . $hiddenField . $this->tag->render() . '</div>';


        //return '<div class="dp-ckeditor dp-ckeditor-' . $this->arguments['config'] . '" data-language="' . $lang . '" data-config="' . htmlspecialchars($jsonConfiguration) . '">' . parent::render() . '</div>';
    }
}
