<?php

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

use FiloBlu\Flow\Block\Adminhtml\Channel\Renderer\OrderStatusFactory;
use FiloBlu\Flow\Block\Adminhtml\Option\MediaGalleryOptionSource;
use FiloBlu\Flow\Block\Adminhtml\Option\ProductAttributeOptionSource;
use FiloBlu\Flow\Helper\Data;
use FiloBlu\Flow\Model\Channel;
use FiloBlu\Flow\Model\Inboundflow;
use Magento\Backend\Block\Template\Context;
use Magento\Backend\Block\Widget\Form\Element\Dependence;
use Magento\Backend\Block\Widget\Form\Generic;
use Magento\Backend\Block\Widget\Tab\TabInterface;
use Magento\Catalog\Model\Product\Visibility;
use Magento\Framework\Data\Form;
use Magento\Framework\Data\FormFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Registry;

/**
 * Class Config
 * @package FiloBlu\Flow\Block\Adminhtml\Channel\Edit\Tab
 */
class Config extends Generic implements TabInterface
{

    const SKU_CONVERSION_LOOKUP_DISABLED = 'disabled';
    const SKU_CONVERSION_LOOKUP_BARCODE = 'barcode';
    const SKU_CONVERSION_LOOKUP_EAN = 'ean';
    const SKU_CONVERSION_LOOKUP_FIELD = 'lookup_sku';

    const INDEXER_STRATEGY_NATIVE = 'native';
    const INDEXER_STRATEGY_FULL = 'full';
    const INDEXER_STRATEGY_FORCE = 'force';

    /**
     * @var OrderStatusFactory
     */
    protected $orderStatusFactory;
    /**
     * @var Data
     */
    protected $helper;
    /**
     * @var ProductAttributeOptionSource
     */
    private $productAttributeOptionSource;
    /**
     * @var MediaGalleryOptionSource
     */
    private $mediaGalleryOptionSource;

    /**
     * @param Data $helper
     * @param Context $context
     * @param Registry $registry
     * @param FormFactory $formFactory
     * @param OrderStatusFactory $orderStatusFactory
     * @param ProductAttributeOptionSource $productAttributeOptionSource
     * @param MediaGalleryOptionSource $mediaGalleryOptionSource
     * @param array $data
     */
    public function __construct(
        Data $helper,
        Context $context,
        Registry $registry,
        FormFactory $formFactory,
        OrderStatusFactory $orderStatusFactory,
        ProductAttributeOptionSource $productAttributeOptionSource,
        MediaGalleryOptionSource $mediaGalleryOptionSource,
        array $data = []
    ) {
        parent::__construct($context, $registry, $formFactory, $data);
        $this->productAttributeOptionSource = $productAttributeOptionSource;
        $this->helper = $helper;
        $this->orderStatusFactory = $orderStatusFactory;
        $this->mediaGalleryOptionSource = $mediaGalleryOptionSource;
    }

    /**
     * Prepare label for tab
     *
     * @return string
     */
    public function getTabLabel()
    {
        return __('Config');
    }

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

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

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

    /**
     * Prepare form
     *
     * @return $this
     * @throws LocalizedException
     */
    protected function _prepareForm()
    {
        $isUrlToolsEnabled = $this->helper->isModuleEnabled('FiloBlu_ProductUrlTools');

        /** @var Channel $model */
        $model = $this->_coreRegistry->registry('flow_channel');

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

        $form->setHtmlIdPrefix('page_');

        $fieldset = $form->addFieldset('config_fieldset', ['legend' => __('Config')]);

        $flow = $fieldset->addField(
            'flow',
            'select',
            [
                'name'     => 'config[flow]',
                'label'    => __('Model / Flow'),
                'required' => true,
                'values'   => $this->helper->getModels(),
                'note'     => 'Per Flow di tipo Multistock: installare anche filoblu/mod2-ext-msi'
            ]
        );

        $fieldset->addField(
            'custom_module_model',
            'text',
            [
                'name'     => 'config[custom_module_model]',
                'label'    => __("Custom Model's Module Name"),
                'required' => false,
                'note'     => 'Se la Model è esterna al modulo flow inserire il nome del modulo nel quale è dichiarata'
            ]
        );

        $groupedChildVisibility = $fieldset->addField(
            'grouped_child_visibility',
            'select',
            [
                'label'   => __('Grouped Child Visibility'),
                'name'    => 'config[grouped_child_visibility]',
                'values'  => \Magento\Catalog\Model\Product\Visibility::getOptionArray(),
                'default' => '',
                'required' => false
            ]
        );

        $fieldset->addField(
            'concurrency',
            'select',
            [
                'name' => 'config[concurrency]',
                'label'    => __('Allow concurrency'),
                'required' => true,
                'values'   => [
                    '0' => 'No',
                    '1' => 'Yes'
                ],
                'default'  => '1',
                'note' => ''
            ]
        );

        $copyToIte = $fieldset->addField(
            'copy_to_ite',
            'select',
            [
                'name'     => 'config[copy_to_ite]',
                'label'    => __('Copy to Ite'),
                'required' => false,
                'values'   => [
                    '0' => 'No',
                    '1' => 'Yes'
                ],
                'default'  => 0,
                'note'     => 'Per Flow di tipo <b>Anagrafica</b>: duplicare il file per generare il corrispondente <b>Ite</b>?'
            ]
        );

        $copyToIteMode = $fieldset->addField(
            'copy_to_ite_mode',
            'select',
            [
                'name'     => 'config[copy_to_ite_mode]',
                'label'    => __('Copy to Ite Mode'),
                'required' => false,
                'values'   => [
                    Channel\Config::COPY_TO_ITE_MODE_AUTO           => 'Auto',
                    Channel\Config::COPY_TO_ITE_MODE_FROM_EAVS_FILE => 'From Eavs file'
                ],
                'default'  => 0,
                'note'     => '<ul><li><b>Auto</b>: genera il nome ite nel formato <quote>ite_20220622_080621.csv</quote></li><li><b>From Eavs File</b>: genera il nome ite partendo dal nome del file anagrafica in ingresso per sostuituzione</li></ul>'
            ]
        );

        $copyToIteFrom = $fieldset->addField(
            'copy_to_ite_replace_from',
            'text',
            [
                'name'  => 'config[copy_to_ite_replace_from]',
                'label' => __('Replace from'),
            ]
        );

        $copyToIteTo = $fieldset->addField(
            'copy_to_ite_replace_to',
            'text',
            [
                'name'  => 'config[copy_to_ite_replace_to]',
                'label' => __('Replace to'),

            ]
        );

        $stripWhiteSpace = $fieldset->addField(
            'strip_white_space',
            'select',
            [
                'name'     => 'config[strip_white_space]',
                'label'    => __('Strip White Spaces From Sku'),
                'required' => false,
                'values'   => [
                    '0' => 'No',
                    '1' => 'Yes'
                ],
                'default'  => '1'
            ]
        );

        $processReservedStock = $fieldset->addField(
            'process_reserved_stock',
            'select',
            [
                'name'     => 'config[process_reserved_stock]',
                'label'    => __('Process Reserved Stock'),
                'required' => false,
                'values'   => [
                    '0' => 'No',
                    '1' => 'Yes'
                ],
                'default'  => '1'
            ]
        );

        $allowRetry = $fieldset->addField(
            'allow_retry',
            'select',
            [
                'name'     => 'config[allow_retry]',
                'label'    => __('Allow Retry on error'),
                'required' => false,
                'values'   => [
                    '0' => 'No',
                    '1' => 'Yes'
                ],
                'default'  => '0'
            ]
        );

        $maxRetryCount = $fieldset->addField(
            'max_retry_count',
            'text',
            [
                'name'     => 'config[max_retry_count]',
                'label'    => __('Max retry count'),
                'required' => false,
                'default'  => '3'
            ]
        );

        $processReservedStockStatus = $fieldset->addField(
            'process_reserved_stock_status',
            'multiselect',
            [
                'name'     => 'config[process_reserved_stock_status]',
                'label'    => __('Add compensations when order status is'),
                'required' => false,
                'values'   => $this->orderStatusFactory->create()->toOptionArray()
            ]
        );

        $stockSource = $fieldset->addField('stock_source', 'select', [
            'label'   => __('Stock Source'),
            'name'    => 'config[stock_source]',
            'values'  => $this->helper->getSources(),
            'default' => 'default',
        ]);

        $discardNoManageStock = $fieldset->addField('discard_no_managed', 'select', [
            'label'   => __('Discard product without stock'),
            'name'    => 'config[discard_no_managed]',
            'values'  => [
                '0' => 'No',
                '1' => 'Yes'
            ],
            'default' => '0',
            'class'   => 'stock-channel-element'
        ]);

        $discardAlreadyProcessedElementsStockAdjustment = $fieldset->addField('discard_already_processed_element', 'select', [
            'label'   => __('Discard already processed order element'),
            'name'    => 'config[discard_already_processed_element]',
            'values'  => [
                '0' => 'No',
                '1' => 'Yes'
            ],
            'default' => '0',
            'class'   => 'stock-channel-element'
        ]);

        $setNotSpecifiedSkuQtyToZero = $fieldset->addField('not_specified_sku_to_zero_qty', 'select', [
            'label'   => __('Set not specified sku qty to zero'),
            'name'    => 'config[not_specified_sku_to_zero_qty]',
            'values'  => [
                '0' => 'No',
                '1' => 'Yes'
            ],
            'default' => '0',
            'note'    => 'Enable it if You want to set zero qty for product not specified in the file',
            'class'   => 'stock-channel-element'
        ]);

        $indexerStrategy = $fieldset->addField('indexer_strategy', 'select', [
            'label'   => __('Chose the indexer strategy'),
            'name'    => 'config[indexer_strategy]',
            'values'  => [
                self::INDEXER_STRATEGY_FULL   => self::INDEXER_STRATEGY_FULL,
                self::INDEXER_STRATEGY_NATIVE => self::INDEXER_STRATEGY_NATIVE,
                self::INDEXER_STRATEGY_FORCE  => self::INDEXER_STRATEGY_FORCE
            ],
            'default' => self::INDEXER_STRATEGY_FULL,
            'class'   => 'stock-channel-element'
        ]);

        $fixInventorySourceItem = $fieldset->addField('fix_inventory_source_item', 'select', [
            'label'   => __('Fix Inventory SourceItem'),
            'name'    => 'config[fix_inventory_source_item]',
            'values'  => [
                '1' => 'Yes',
                '0' => 'No'
            ],
            'default' => '0',
            'class'   => 'stock-channel-element',
            'note'    => 'Remvoes all products differente form simple inside inventory_source_item table'
        ]);

        $skuConversionLookup = $fieldset->addField(
            'sku_conversion_lookup',
            'select',
            [
                'label'   => __('SKU conversion lookup'),
                'name'    => 'config[sku_conversion_lookup]',
                'values'  => [
                    self::SKU_CONVERSION_LOOKUP_DISABLED => self::SKU_CONVERSION_LOOKUP_DISABLED,
                    self::SKU_CONVERSION_LOOKUP_BARCODE  => self::SKU_CONVERSION_LOOKUP_BARCODE,
                    self::SKU_CONVERSION_LOOKUP_EAN      => self::SKU_CONVERSION_LOOKUP_EAN,
                ],
                'default' => self::SKU_CONVERSION_LOOKUP_DISABLED,
                'note'    => 'Questo attributo viene usato assieme al valore, se presente, della colonna \'lookup_sku\' (flow_from_stock) per calcolare lo SKU',
            ]
        );

        $preorderDiscard = $fieldset->addField(
            'preorder_discard',
            'select',
            [
                'name'     => 'config[preorder_discard]',
                'label'    => __('Discard Preorder'),
                'required' => false,
                'values'   => [
                    '0' => 'No',
                    '1' => 'Yes'
                ],
                'default'  => '0',
            ]
        );

        $allowProcessZeroPrices = $fieldset->addField(
            'allow_process_zero_prices',
            'select',
            [
                'name'     => 'config[allow_process_zero_prices]',
                'label'    => __('Allow 0 prices to be processed'),
                'required' => false,
                'values'   => [
                    '0' => 'No',
                    '1' => 'Yes'
                ],
                'default'  => '0',
            ]
        );

        $warningEmailForZeroPrices = $fieldset->addField(
            'warning_email_for_zero_prices',
            'select',
            [
                'name'     => 'config[warning_email_for_zero_prices]',
                'label'    => __('Send warning email for 0 prices'),
                'required' => false,
                'values'   => [
                    '0' => 'No',
                    '1' => 'Yes'
                ],
                'default'  => '0',
            ]
        );

        $emailToAlert = $fieldset->addField(
            'email_to_alert_for_zero_prices',
            'text',
            [
                'name'     => 'config[email_to_alert_for_zero_prices]',
                'label'    => __('Email to alert for 0 prices'),
                'required' => false,
                'note'     => 'Comma separated list of emails to alert when a 0 price is found in the file',
            ]
        );

        $preorderAttributeCode = $fieldset->addField(
            'preorder_attribute_code',
            'select',
            [
                'name'     => 'config[preorder_attribute_code]',
                'label'    => __('Preorder attribute'),
                'required' => false,
                'values'   => $this->productAttributeOptionSource->toOptionArray()
            ]
        );

        $preorderAttributeValue = $fieldset->addField(
            'preorder_attribute_value',
            'text',
            [
                'name'     => 'config[preorder_attribute_value]',
                'label'    => __('Preorder Attribute Value'),
                'required' => false
            ]
        );

        $iteChannelName = $fieldset->addField(
            'ite_channel_name',
            'text',
            [
                'name'     => 'config[ite_channel_name]',
                'label'    => __('Ite channel name'),
                'required' => false
            ]
        );

        $fieldset->addField('bus', 'select', [
            'label'   => __('Bus'),
            'name'    => 'config[bus]',
            'values'  => [
                '1' => '1',
                '2' => '2',
                '3' => '3',
                '4' => '4'
            ],
            'default' => '1'
        ]);

        $fieldset->addField('priority', 'select', [
            'label'   => __('Priority'),
            'name'    => 'config[priority]',
            'values'  => Inboundflow::getPriorityList(),
            'default' => Inboundflow::PRIORITY_LOW
        ]);

        $fieldset->addField('kill_after', 'text', [
            'label'   => __('Kill After (minutes)'),
            'name'    => 'config[kill_after]',
            'default' => 20
        ]);

        $fieldset->addField('type', 'select', [
            'label'   => __('Channel Type'),
            'name'    => 'config[type]',
            'values'  => [
                'file'     => 'File',
                'image'    => 'Image',
                'video'    => 'Video',
                'document' => 'Document',
                'swatch'   => 'Swatch'
            ],
            'default' => 'file'
        ]);

        $imageMediaGallery = $fieldset->addField(
            'image_media_gallery',
            'select',
            [
                'name'     => 'config[image_media_gallery]',
                'label'    => __('Image Media Gallery'),
                'required' => false,
                'values'   => $this->mediaGalleryOptionSource->toOptionArray(),
                'default'  => 'media_gallery',
            ]
        );

        $dbTableName = $fieldset->addField(
            'db_table_name',
            'text',
            [
                'name'     => 'config[db_table_name]',
                'label'    => __('Db Table Name'),
                'required' => true
            ]
        );

        $sizeguideTitle = $fieldset->addField(
            'sizeguide_title',
            'text',
            [
                'name'     => 'config[sizeguide_title]',
                'label'    => __('Title table size guide'),
                'required' => false,
                'placeholder'  => 'SIZE GUIDE'
            ]
        );

        $sizeguideTitlePlaceholder = $fieldset->addField(
            'sizeguide_title_placeholder',
            'text',
            [
                'name'     => 'config[sizeguide_title_placeholder]',
                'label'    => __('Placeholder title'),
                'required' => false,
                'placeholder'  => '{{TABLE-TITLE}}'
            ]
        );

        $sizeguideStyleContainer = $fieldset->addField(
            'sizeguide_style_container',
            'text',
            [
                'name'     => 'config[sizeguide_style_container]',
                'label'    => __('Style size guide container'),
                'required' => false,
                'placeholder'  => 'put here class and style inline'
            ]
        );

        $sizeguideStyleContainerPlaceholder = $fieldset->addField(
            'sizeguide_stylecontainer_placeholder',
            'text',
            [
                'name'     => 'config[sizeguide_stylecontainer_placeholder]',
                'label'    => __('Placeholder style container'),
                'required' => false,
                'placeholder'  => '{{STYLE-CONTAINER}}'
            ]
        );

        $sizeguideStyleTable = $fieldset->addField(
            'sizeguide_style_table',
            'text',
            [
                'name'     => 'config[sizeguide_style_table]',
                'label'    => __('Style size guide table'),
                'required' => false,
                'placeholder'  => 'put here class and style inline'
            ]
        );

        $sizeguideStyleTablePlaceholder = $fieldset->addField(
            'sizeguide_styletable_placeholder',
            'text',
            [
                'name'     => 'config[sizeguide_styletable_placeholder]',
                'label'    => __('Placeholder style table'),
                'required' => false,
                'placeholder'  => '{{STYLE-TABLE}}'
            ]
        );

        $sizeguideStyleRowHeader = $fieldset->addField(
            'sizeguide_style_row_header',
            'text',
            [
                'name'     => 'config[sizeguide_style_row_header]',
                'label'    => __('Style header row'),
                'required' => false,
                'placeholder'  => 'put here class and style inline'
            ]
        );

        $sizeguideStyleCellsHeader = $fieldset->addField(
            'sizeguide_style_cells_header',
            'text',
            [
                'name'     => 'config[sizeguide_style_cells_header]',
                'label'    => __('Style header cells'),
                'required' => false,
                'placeholder'  => 'put here class and style inline'
            ]
        );

        $sizeguideStyleOddRows = $fieldset->addField(
            'sizeguide_style_odd_rows',
            'text',
            [
                'name'     => 'config[sizeguide_style_odd_rows]',
                'label'    => __('Style odd rows'),
                'required' => false,
                'placeholder'  => 'put here class and style inline'
            ]
        );

        $sizeguideStyleEvenRows = $fieldset->addField(
            'sizeguide_style_even_rows',
            'text',
            [
                'name'     => 'config[sizeguide_style_even_rows]',
                'label'    => __('Style even rows'),
                'required' => false,
                'placeholder'  => 'put here class and style inline'
            ]
        );

        $sizeguideStyleRowsCells = $fieldset->addField(
            'sizeguide_style_rows_cells',
            'text',
            [
                'name'     => 'config[sizeguide_style_rows_cells]',
                'label'    => __('Style all cells (no header)'),
                'required' => false,
                'placeholder'  => 'put here class and style inline'
            ]
        );

        $sizeguideRowsPlaceholder = $fieldset->addField(
            'sizeguide_rows_placeholder',
            'text',
            [
                'name'     => 'config[sizeguide_rows_placeholder]',
                'label'    => __('Placeholder table rows'),
                'required' => false,
                'placeholder'  => '{{TABLE-ROWS}}'
            ]
        );

        $sizeguideHtml = $fieldset->addField(
            'sizeguide_html',
            'textarea',
            [
                'name'     => 'config[sizeguide_html]',
                'label'    => __('Size guide body tml'),
                'required' => false,
                'rows'  => 25,
                'placeholder'  => '<div {{STYLE-CONTAINER}}>
                                    <br class="Apple-interchange-newline">
                                    <p><strong>{{TABLE-TITLE}}</strong></p>
                                    <table {{STYLE-TABLE}}>
                                        <tbody>
                                        {{TABLE-ROWS}}
                                        </tbody>
                                    </table>
                                </div>'
            ]
        );

        $createCompany = $fieldset->addField(
            'create_company_with_customer',
            'select',
            [
                'name'     => 'config[create_company_with_customer]',
                'label'    => __('Create company with customer data'),
                'required' => false,
                'values'   => [
                    '0' => 'No',
                    '1' => 'Yes'
                ],
                'default'  => '0',
            ]
        );

        $automaticBundleDefaultOptionSet = $fieldset->addField(
            'automatic_bundle_default_option_set',
            'select',
            [
                'name'     => 'config[automatic_bundle_default_option_set]',
                'label'    => __('Allow automatic bundle default option set'),
                'required' => false,
                'values'   => [
                    '0' => 'No',
                    '1' => 'Yes'
                ],
                'default'  => '1',
            ]
        );

        $enableAttachDocument = $fieldset->addField(
            'enable_attach_document',
            'select',
            [
                'name'     => 'config[enable_attach_document]',
                'label'    => __('Enable attach document to entity'),
                'required' => false,
                'values'   => [
                    '0' => 'No',
                    '1' => 'Yes'
                ],
                'default'  => '0'
            ]
        );

        $attachEntity = $fieldset->addField(
            'entity_attach_document',
            'select',
            [
                'name'     => 'config[entity_attach_document]',
                'label'    => __('Entity type to which to attach document'),
                'required' => false,
                'values'   => [
                    '0' => 'None',
                    'product' => 'Product'
                ],
                'default'  => '0'
            ]
        );

        $docAttrCode = $fieldset->addField(
            'attr_code_for_document',
            'text',
            [
                'name'     => 'config[attr_code_for_document]',
                'label'    => __('Attribute code for document'),
                'required' => false,
                'note'     => 'Code of the attribute that will contain the reference to the document'
            ]
        );

        $docEntityIdentifier = $fieldset->addField(
            'document_entity_identifier',
            'select',
            [
                'name'     => 'config[document_entity_identifier]',
                'label'    => __('Entity identified by'),
                'required' => false,
                'values'   => [
                    'entity_id' => 'ID',
                    'sku' => 'SKU'
                ],
                'default'  => '0'
            ]
        );

        $entIdentifierPosition = $fieldset->addField(
            'entity_identifier_position',
            'text',
            [
                'name'     => 'config[entity_identifier_position]',
                'label'    => __('Entity identifier position'),
                'required' => false,
                'note'     => 'Position of the identifier value within the file name from 1 to n'
            ]
        );

        $docAttrByStore = $fieldset->addField(
            'document_attribute_by_store',
            'select',
            [
                'name'     => 'config[document_attribute_by_store]',
                'label'    => __('Enable set document by store'),
                'required' => false,
                'values'   => [
                    '0' => 'No',
                    '1' => 'Yes'
                ],
                'default'  => '0'
            ]
        );

        $docStorePosition = $fieldset->addField(
            'document_store_position',
            'text',
            [
                'name'     => 'config[document_store_position]',
                'label'    => __('Store ID position'),
                'required' => false,
                'note'     => 'Position of the store ID within the file name from 1 to n (for multiple store ids separate the positions with a comma)'
            ]
        );

        $docFileSeparator = $fieldset->addField(
            'document_filename_separator',
            'text',
            [
                'name'     => 'config[document_filename_separator]',
                'label'    => __('Filename separator'),
                'required' => false,
                'note'     => 'Document filename separator'
            ]
        );

        if($isUrlToolsEnabled)
        {
            $generateUrlKey = $fieldset->addField(
                'generate_url_key_on_parse',
                'select',
                [
                    'name'     => 'config[generate_url_key_on_parse]',
                    'label'    => __('Generate Url Key On Parse'),
                    'required' => false,
                    'values'   => [
                        '0' => 'No',
                        '1' => 'Yes'
                    ],
                    'default'  => '0'
                ]
            );
        }

        $simplePriceFromConfigurable = $fieldset->addField(
            'simple_price_from_configurable',
            'select',
            [
                'name'     => 'config[simple_price_from_configurable]',
                'label'    => __('Copy price from configurable product'),
                'note'     => 'When creating a new simple product, copy the price from the configurable product',
                'required' => false,
                'values'   => [
                    '0' => 'No',
                    '1' => 'Yes'
                ],
                'default'  => '0'
            ]
        );

        // Generate mapping for javascript

        $mapperBlock = $this->getLayout()->createBlock(Dependence::class);
        $mapperBlock->addFieldMap($flow->getHtmlId(), $flow->getName())
            ->addFieldMap($copyToIte->getHtmlId(), $copyToIte->getName())
            ->addFieldMap($iteChannelName->getHtmlId(), $iteChannelName->getName())
            ->addFieldMap($discardNoManageStock->getHtmlId(), $discardNoManageStock->getName())
            ->addFieldMap($discardAlreadyProcessedElementsStockAdjustment->getHtmlId(), $discardAlreadyProcessedElementsStockAdjustment->getName())
            ->addFieldMap($setNotSpecifiedSkuQtyToZero->getHtmlId(), $setNotSpecifiedSkuQtyToZero->getName())
            ->addFieldMap($stockSource->getHtmlId(), $stockSource->getName())
            ->addFieldMap($indexerStrategy->getHtmlId(), $indexerStrategy->getName())
            ->addFieldMap($fixInventorySourceItem->getHtmlId(), $fixInventorySourceItem->getName())
            ->addFieldMap($skuConversionLookup->getHtmlId(), $skuConversionLookup->getName())
            ->addFieldMap($preorderDiscard->getHtmlId(), $preorderDiscard->getName())
            ->addFieldMap($preorderAttributeCode->getHtmlId(), $preorderAttributeCode->getName())
            ->addFieldMap($preorderAttributeValue->getHtmlId(), $preorderAttributeValue->getName())
            ->addFieldMap($processReservedStockStatus->getHtmlId(), $processReservedStockStatus->getName())
            ->addFieldMap($processReservedStock->getHtmlId(), $processReservedStock->getName())
            ->addFieldMap($imageMediaGallery->getHtmlId(), $imageMediaGallery->getName())
            ->addFieldMap($allowProcessZeroPrices->getHtmlId(), $allowProcessZeroPrices->getName())
            ->addFieldMap($warningEmailForZeroPrices->getHtmlId(), $warningEmailForZeroPrices->getName())
            ->addFieldMap($emailToAlert->getHtmlId(), $emailToAlert->getName())
            ->addFieldMap($stripWhiteSpace->getHtmlId(), $stripWhiteSpace->getName())
            ->addFieldMap($allowRetry->getHtmlId(), $allowRetry->getName())
            ->addFieldMap($maxRetryCount->getHtmlId(), $maxRetryCount->getName())
            ->addFieldMap($copyToIteMode->getHtmlId(), $copyToIteMode->getName())
            ->addFieldMap($copyToIteFrom->getHtmlId(), $copyToIteFrom->getName())
            ->addFieldMap($copyToIteTo->getHtmlId(), $copyToIteTo->getName())
            ->addFieldMap($dbTableName->getHtmlId(), $dbTableName->getName())
            ->addFieldMap($sizeguideTitle->getHtmlId(), $sizeguideTitle->getName())
            ->addFieldMap($sizeguideTitlePlaceholder->getHtmlId(), $sizeguideTitlePlaceholder->getName())
            ->addFieldMap($sizeguideStyleContainer->getHtmlId(), $sizeguideStyleContainer->getName())
            ->addFieldMap($sizeguideStyleContainerPlaceholder->getHtmlId(), $sizeguideStyleContainerPlaceholder->getName())
            ->addFieldMap($sizeguideStyleTable->getHtmlId(), $sizeguideStyleTable->getName())
            ->addFieldMap($sizeguideStyleTablePlaceholder->getHtmlId(), $sizeguideStyleTablePlaceholder->getName())
            ->addFieldMap($sizeguideStyleRowHeader->getHtmlId(), $sizeguideStyleRowHeader->getName())
            ->addFieldMap($sizeguideStyleCellsHeader->getHtmlId(), $sizeguideStyleCellsHeader->getName())
            ->addFieldMap($sizeguideStyleOddRows->getHtmlId(), $sizeguideStyleOddRows->getName())
            ->addFieldMap($sizeguideStyleEvenRows->getHtmlId(), $sizeguideStyleEvenRows->getName())
            ->addFieldMap($sizeguideStyleRowsCells->getHtmlId(), $sizeguideStyleRowsCells->getName())
            ->addFieldMap($sizeguideRowsPlaceholder->getHtmlId(), $sizeguideRowsPlaceholder->getName())
            ->addFieldMap($sizeguideHtml->getHtmlId(), $sizeguideHtml->getName())
            ->addFieldMap($groupedChildVisibility->getHtmlId(), $groupedChildVisibility->getName())
            ->addFieldMap($createCompany->getHtmlId(), $createCompany->getName())
            ->addFieldMap($automaticBundleDefaultOptionSet->getHtmlId(), $automaticBundleDefaultOptionSet->getName())
            ->addFieldMap($enableAttachDocument->getHtmlId(), $enableAttachDocument->getName())
            ->addFieldMap($attachEntity->getHtmlId(), $attachEntity->getName())
            ->addFieldMap($docAttrCode->getHtmlId(), $docAttrCode->getName())
            ->addFieldMap($docEntityIdentifier->getHtmlId(), $docEntityIdentifier->getName())
            ->addFieldMap($entIdentifierPosition->getHtmlId(), $entIdentifierPosition->getName())
            ->addFieldMap($docAttrByStore->getHtmlId(), $docAttrByStore->getName())
            ->addFieldMap($docStorePosition->getHtmlId(), $docStorePosition->getName())
            ->addFieldMap($docFileSeparator->getHtmlId(), $docFileSeparator->getName())
            ->addFieldMap($simplePriceFromConfigurable->getHtmlId(), $simplePriceFromConfigurable->getName())
        ;

         if($isUrlToolsEnabled){
             $mapperBlock->addFieldMap($generateUrlKey->getHtmlId(), $generateUrlKey->getName());
             $mapperBlock->addFieldDependence($generateUrlKey->getName(), $flow->getName(), 'From\\Eavs');
         }

         $mapperBlock->addFieldDependence($iteChannelName->getName(), $copyToIte->getName(), '1')
            ->addFieldDependence($processReservedStockStatus->getName(), $processReservedStock->getName(), '1')
            ->addFieldDependence($preorderAttributeCode->getName(), $preorderDiscard->getName(), '1')
            ->addFieldDependence($preorderAttributeValue->getName(), $preorderDiscard->getName(), '1')
            ->addFieldDependence($copyToIte->getName(), $flow->getName(), 'From\\Eavs')
            ->addFieldDependence($iteChannelName->getName(), $flow->getName(), 'From\\Eavs')
            ->addFieldDependence($discardNoManageStock->getName(), $flow->getName(), 'From\\Stock')
            ->addFieldDependence($discardAlreadyProcessedElementsStockAdjustment->getName(), $flow->getName(), 'From\\StockAdjustment')
            ->addFieldDependence($setNotSpecifiedSkuQtyToZero->getName(), $flow->getName(), 'From\\Stock')
            ->addFieldDependence($stockSource->getName(), $flow->getName(), 'From\\Stock')
            ->addFieldDependence($indexerStrategy->getName(), $flow->getName(), 'From\\Stock')
            ->addFieldDependence($skuConversionLookup->getName(), $flow->getName(), 'From\\Stock')
            ->addFieldDependence($preorderDiscard->getName(), $flow->getName(), 'From\\Stock')
            ->addFieldDependence($preorderAttributeCode->getName(), $flow->getName(), 'From\\Stock')
            ->addFieldDependence($preorderAttributeValue->getName(), $flow->getName(), 'From\\Stock')
            ->addFieldDependence($processReservedStock->getName(), $flow->getName(), 'From\\Stock')
            ->addFieldDependence($processReservedStockStatus->getName(), $flow->getName(), 'From\\Stock')
            ->addFieldDependence($fixInventorySourceItem->getName(), $flow->getName(), 'From\\Stock')
            ->addFieldDependence($imageMediaGallery->getName(), $flow->getName(), 'Imagesflow')
            ->addFieldDependence($allowProcessZeroPrices->getName(), $flow->getName(), 'From\\Price')
            ->addFieldDependence($warningEmailForZeroPrices->getName(), $flow->getName(), 'From\\Price')
            ->addFieldDependence($emailToAlert->getName(), $flow->getName(), 'From\\Price')
            ->addFieldDependence($stripWhiteSpace->getName(), $flow->getName(), 'From\\Product')
            ->addFieldDependence($simplePriceFromConfigurable->getName(), $flow->getName(), 'From\\Product')
            ->addFieldDependence($maxRetryCount->getName(), $allowRetry->getName(), '1')
            ->addFieldDependence($copyToIteFrom->getName(), $flow->getName(), 'From\\Eavs')
            ->addFieldDependence($copyToIteTo->getName(), $flow->getName(), 'From\\Eavs')
            ->addFieldDependence($copyToIteMode->getName(), $flow->getName(), 'From\\Eavs')
            ->addFieldDependence($copyToIteFrom->getName(), $copyToIte->getName(), '1')
            ->addFieldDependence($copyToIteTo->getName(), $copyToIte->getName(), '1')
            ->addFieldDependence($copyToIteMode->getName(), $copyToIte->getName(), '1')
            ->addFieldDependence($sizeguideTitle->getName(), $flow->getName(), 'From\\Sizeguide')
            ->addFieldDependence($sizeguideTitlePlaceholder->getName(), $flow->getName(), 'From\\Sizeguide')
            ->addFieldDependence($sizeguideStyleContainer->getName(), $flow->getName(), 'From\\Sizeguide')
            ->addFieldDependence($sizeguideStyleContainerPlaceholder->getName(), $flow->getName(), 'From\\Sizeguide')
            ->addFieldDependence($sizeguideStyleTable->getName(), $flow->getName(), 'From\\Sizeguide')
            ->addFieldDependence($sizeguideStyleTablePlaceholder->getName(), $flow->getName(), 'From\\Sizeguide')
            ->addFieldDependence($sizeguideStyleRowHeader->getName(), $flow->getName(), 'From\\Sizeguide')
            ->addFieldDependence($sizeguideStyleCellsHeader->getName(), $flow->getName(), 'From\\Sizeguide')
            ->addFieldDependence($sizeguideStyleOddRows->getName(), $flow->getName(), 'From\\Sizeguide')
            ->addFieldDependence($sizeguideStyleEvenRows->getName(), $flow->getName(), 'From\\Sizeguide')
            ->addFieldDependence($sizeguideStyleRowsCells->getName(), $flow->getName(), 'From\\Sizeguide')
            ->addFieldDependence($sizeguideRowsPlaceholder->getName(), $flow->getName(), 'From\\Sizeguide')
            ->addFieldDependence($sizeguideHtml->getName(), $flow->getName(), 'From\\Sizeguide')
            ->addFieldDependence($groupedChildVisibility->getName(), $flow->getName(), 'From\\Grouped')
            ->addFieldDependence($createCompany->getName(), $flow->getName(), 'From\\Customer')
            ->addFieldDependence($automaticBundleDefaultOptionSet->getName(), $flow->getName(), 'From\\Bundle')
            ->addFieldDependence($enableAttachDocument->getName(), $flow->getName(), 'Document')
            ->addFieldDependence($attachEntity->getName(), $enableAttachDocument->getName(), '1')
            ->addFieldDependence($docAttrCode->getName(), $enableAttachDocument->getName(), '1')
            ->addFieldDependence($docEntityIdentifier->getName(), $enableAttachDocument->getName(), '1')
            ->addFieldDependence($entIdentifierPosition->getName(), $enableAttachDocument->getName(), '1')
            ->addFieldDependence($docAttrByStore->getName(), $enableAttachDocument->getName(), '1')
            ->addFieldDependence($docStorePosition->getName(), $docAttrByStore->getName(), '1')
            ->addFieldDependence($docFileSeparator->getName(), $enableAttachDocument->getName(), '1')
            ->addFieldDependence(
                $copyToIteFrom->getName(),
                $copyToIteMode->getName(),
                Channel\Config::COPY_TO_ITE_MODE_FROM_EAVS_FILE
            )
            ->addFieldDependence(
                $copyToIteTo->getName(),
                $copyToIteMode->getName(),
                Channel\Config::COPY_TO_ITE_MODE_FROM_EAVS_FILE
            )
            ->addFieldDependence(
                $dbTableName->getName(),
                $flow->getName(),
                'TableFlow'
            );

        $this->setChild('form_after',$mapperBlock);

        $form->setValues($model->getData('config'));
        $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);
    }
}
