<?php

namespace FiloBlu\Flow\Block\Adminhtml\Channel\Edit\Tab;

use FiloBlu\Flow\Block\Adminhtml\Channel\Renderer\Textjson;
use FiloBlu\Flow\Model\Channel;
use Magento\Backend\Block\Widget\Form\Element\Dependence;
use Magento\Backend\Block\Widget\Form\Generic;
use Magento\Backend\Block\Widget\Tab\TabInterface;
use Magento\Framework\Data\Form;
use Magento\Framework\Exception\LocalizedException;

/**
 * Class Map
 * @package FiloBlu\Flow\Block\Adminhtml\Channel\Edit\Tab
 */
class Map extends Generic implements TabInterface
{
    /**
     * Prepare label for tab
     *
     * @return string
     */
    public function getTabLabel()
    {
        return __('Map');
    }

    /**
     * Prepare title for tab
     *
     * @return string
     */
    public function getTabTitle()
    {
        return __('map');
    }

    /**
     * {@inheritdoc}
     */
    public function canShowTab()
    {
        return true;
    }

    /**
     * {@inheritdoc}
     */
    public function isHidden()
    {
        return false;
    }

    /**
     * Prepare form
     *
     * @return $this
     * @throws LocalizedException
     */
    protected function _prepareForm()
    {
        /** @var Channel $model */
        $model = $this->_coreRegistry->registry('flow_channel');

        /** @var Form $form */
        $form = $this->_formFactory->create();

        $form->setHtmlIdPrefix('page_');

        $fieldset = $form
            ->addFieldset('map_fieldset', [
                'legend' => __('Map')
            ])
            ->addType(
                'textjson',
                Textjson::class
            );

        // TODO:
        // - use uiComponent based form
        // - use switcherConfig to hide map textarea conditionally

        $useMap = $fieldset->addField('use_map', 'select', [
            'label'   => __('Use mapping file'),
            'name'    => 'use_map',
            'values'  => [
                '0' => 'No',
                '1' => 'Yes'
            ],
            'default' => '0'
        ]);

        $map = $fieldset->addField('map', 'textjson', [
            'label' => __('Map JSON'),
            'name'  => 'map',
            'rows'  => 50,
            'cols'  => 40
        ]);

        $this->setChild(
            'form_after',
            $this->getLayout()->createBlock(Dependence::class)
                ->addFieldMap($useMap->getHtmlId(), $useMap->getName())
                ->addFieldMap($map->getHtmlId(), $map->getName())
                ->addFieldDependence($map->getName(), $useMap->getName(), '1')
        );

        $form->setValues($model->getData());
        $this->setForm($form);

        return parent::_prepareForm();
    }

    /**
     * Check permission for passed action
     *
     * @param string $resourceId
     * @return bool
     */
    protected function _isAllowedAction($resourceId)
    {
        return $this->_authorization->isAllowed($resourceId);
    }
}
