<?php

namespace Internetgalerie\IgDatapoolFe\ViewHelpers\Form;

use Internetgalerie\IgCoreViewhelpers\ViewHelpers\Form\TextfieldViewHelper;
use TYPO3\CMS\Core\Page\PageRenderer;

/**
 * Renders an slider next to the input text field.
 *
 * = Examples =
 *
 * <code title="Example">
 * <dp:form.slider property="name2" min="0" max="10" step="0.5" orientation="vertical" default="5"  />
 * </code>
 *
 * You can also use the "property" attribute if you have bound an object to the form.
 * See <f:form> for more documentation.
 */
class SliderViewHelper extends TextfieldViewHelper
{

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

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

    /**
     * Initialize the arguments.
     *
     * @return void
     * @api
     */
    public function initializeArguments(): void
    {
        parent::initializeArguments();
        $this->registerArgument('min', 'int', 'Minimum Value', false, 0);
        $this->registerArgument('max', 'int', 'Maximum Value', false, 100);
        $this->registerArgument('step', 'float', 'Step', false, 1);
        $this->registerArgument('orientation', 'string', 'horizontal or vertical', false);
        $this->registerArgument('default', 'mixed', 'Default Value');
    }

    /**
     * Renders the hidden field.
     *
     * @return string
     * @api
     */
    public function render(): string
    {
        //$this->tag->addAttribute('readonly', 'readonly');
        $this->tag->addAttribute('data-min', intval($this->arguments['min']));
        $this->tag->addAttribute('data-max', intval($this->arguments['max']));
        $this->tag->addAttribute('data-step', ($this->arguments['step']));
        if ($this->arguments['orientation']=='vertical') {
            $this->tag->addAttribute('data-orientation', 'vertical');
        }
        // default gesetzt, kein value, nicht abgeschickt mit fehlern ($this->getLastSubmittedFormData()) ist object(mit property und habe keinen object Wert)
        if (isset($this->arguments['default']) && !$this->hasArgument('value') && !$this->hasMappingErrorOccurred() && $this->isObjectAccessorMode() && $this->getPropertyValue()===null) {
            $this->arguments['value']=$this->arguments['default'];
        }
        $field = parent::render();
        $this->pageRenderer->addJsFooterLibrary('nouislider', 'EXT:ig_datapool_fe/Resources/Public/JavaScript/noUiSlider/nouislider.js');
        //$this->pageRenderer->addJsFooterLibrary('nouislider-init', 'EXT:ig_datapool_fe/Resources/Public/JavaScript/noUiSlider/nouislider-init.js');
        $this->pageRenderer->addCssFile('EXT:ig_datapool_fe/Resources/Public/Css/nouislider.css');
        $this->pageRenderer->loadJavaScriptModule('@dp/elements/noUiSlider.js');


        return '<div class="dp-slider"><div class="sliderWrapper"><div class="slider"></div></div>' . $field . '</div>';
    }
}
