<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers\Form;

use TYPO3\CMS\Core\Utility\VersionNumberUtility;
use Internetgalerie\IgCoreViewhelpers\ViewHelpers\Form\TextareaViewHelper;
use TYPO3\CMS\Core\Page\AssetCollector;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Core\Utility\PathUtility;
use TYPO3\CMS\Extbase\Configuration\ConfigurationManagerInterface;

/**
 * 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);
        $rteDefaultConfig = $this->settings['plugin.']['ig_datapool_fe.']['settings.']['rte.']['default'];
        $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']) . ']');
        }
        $siteLanguage = $GLOBALS['TYPO3_REQUEST']->getAttribute('language');
        $lang = $siteLanguage->getLocale()->getLanguageCode();
        $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((string) $rteSettings[$this->arguments['config']]);
            $configObject = json_decode($config);
            /*
            $configObject->plugins = [
                'Essentials',
                'Bold',
                'Italic',
                //'Heading',
                'Link',
                'Paragraph',
                //'Table',
                //'TableToolbar',
            ];
            */
            //if ($config) {                var_dump($config, $configObject);exit(0);            }
        } else {
            $config = trim($rteSettings[$rteDefaultConfig] ?? $rteSettings['basicstyles']);
            $configObject = json_decode($config);
            //var_dump($configObject, $config );exit(0); 
            $configuration['toolbar'] = $configObject->toolbar;
        }

        $jsonConfiguration= json_encode($configObject); // Funktioniert nur so, ohne decode und encode wills nicht gehen, liegt wohl an speziellen zeichen

        $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 (VersionNumberUtility::convertVersionNumberToInteger(VersionNumberUtility::getNumericTypo3Version()) >= 12000000) {
            $editorBasePath = PathUtility::getPublicResourceWebPath('EXT:ig_datapool_fe/Resources/Public/Contrib/ckeditor5/');
            $importmapSrc = '{
                                "imports": {
                                        "ckeditor5": "' . $editorBasePath . 'ckeditor5.js",
                                        "ckeditor5/": "' . $editorBasePath . '"
                                }
                        }';

            $assetCollector = GeneralUtility::makeInstance(AssetCollector::class);
            $assetCollector->addStyleSheet('ig-datapool-fe-ckeditor5', 'EXT:ig_datapool_fe/Resources/Public/Contrib/ckeditor5/ckeditor5.css');

            // BUG v12 adds ; to the end
            $assetCollector->addInlineJavaScript('ig-datapool-fe-ckeditor5-imports', $importmapSrc .'</script><script>', ['type' => 'importmap'], ['priority' => true]);


            $assetCollector->addJavaScript('ig-datapool-fe-ckeditor5-module', 'EXT:ig_datapool_fe/Resources/Public/JavaScript/Plugin/Elements/ckeditor5.js', ['type' => 'module']);

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