<?php

namespace FiloBlu\Flow\Block\Adminhtml\Channel\Renderer;

use FiloBlu\Flow\Helper\Data;
use Magento\Framework\Data\Form\Element\AbstractElement;
use Magento\Framework\Data\Form\Element\CollectionFactory;
use Magento\Framework\Data\Form\Element\Factory;
use Magento\Framework\Escaper;

/**
 * Class Textjson
 * @package FiloBlu\Flow\Block\Adminhtml\Channel\Renderer
 */
class Textjson extends AbstractElement
{
    protected $_element;

    /**
     * Default number of rows
     */
    const DEFAULT_ROWS = 4;

    /**
     * Default number of columns
     */
    const DEFAULT_COLS = 15;

    /**
     * @param Factory $factoryElement
     * @param CollectionFactory $factoryCollection
     * @param Escaper $escaper
     * @param Data $helper
     * @param array $data
     */
    public function __construct(
        Factory $factoryElement,
        CollectionFactory $factoryCollection,
        Escaper $escaper,
        Data $helper,
        $data = []
    ) {
        parent::__construct($factoryElement, $factoryCollection, $escaper, $data);
        $this->setType('textjson');
        $this->setExtType('textjson');
        $this->helper = $helper;
        if (!$this->getRows()) {
            $this->setRows(self::DEFAULT_ROWS);
        }
        if (!$this->getCols()) {
            $this->setCols(self::DEFAULT_COLS);
        }
    }

    /**
     * Return the HTML attributes
     *
     * @return string[]
     */
    public function getHtmlAttributes()
    {
        return [
            'title',
            'class',
            'style',
            'onclick',
            'onchange',
            'rows',
            'cols',
            'readonly',
            'disabled',
            'onkeyup',
            'tabindex',
            'data-form-part',
            'data-role',
            'data-action'
        ];
    }

    public function getElementHtml()
    {
        $json=$this->getValue();
        if (!$this->getValue()) {
            $json = $this->helper->getSkeleton();
        }
        $json_decoded = json_decode($json);
        $error = '';
        $value = '';
        // se il json non è valido, stampo dati grezzi + messaggio di errore
        if($json_decoded === null) {
            $value = $json;
            $error = 'Json non valido. Error code: ' . json_last_error() . ' - Error message: ' . json_last_error_msg();
        } else {
            $value = json_encode($json_decoded, JSON_PRETTY_PRINT);
        }

        $this->addClass('textarea admin__control-textarea');
        $html = '';

        if($error) {
            $html .= "<div style='color: #ff0a09;'>{$error}</div>";
        }

        $html .= '<textarea id="' . $this->getHtmlId() . '" name="' . $this->getName() . '" '
            . $this->serialize($this->getHtmlAttributes()) . $this->_getUiId() . ' >';

        $html .= $value;

        $html .= "</textarea>";
        $html .= $this->getAfterElementHtml();

        return $html;
    }

}
