<?php

/**
 * Copyright © 2018 Wyomind. All rights reserved.
 * See LICENSE.txt for license details.
 */

namespace Wyomind\ElasticsearchCore\Block\Adminhtml\System\Config\Form\Field;

/**
 * Config field for the selection of the product attributes filterable in the layered navigation
 */
class AttributesAdvanced extends \Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray
{
    /**
     * Columns of the grid
     * @var array
     */
    protected $_columns = [];

    /**
     * Renderer of the product attributes dropdown
     * @var \Wyomind\ElasticsearchCore\Block\Adminhtml\System\Config\Form\Field\Renderer\FilterableAttributes
     */
    private $_filterableAttributesRenderer;

    /**
     * @var \Wyomind\ElasticsearchCore\Block\Adminhtml\System\Config\Form\Field\Renderer\Closed
     */
    private $_closedRenderer;

    /**
     * @var \Wyomind\ElasticsearchCore\Block\Adminhtml\System\Config\Form\Field\Renderer\GenerateUrl
     */
    private $_generateUrlRenderer;

    /**
     * Rendered of the yes/no dropdown to display or not the number of products for each attribute values
     * @var \Wyomind\ElasticsearchCore\Block\Adminhtml\System\Config\Form\Field\Renderer\ShowResultsCount
     */
    private $_showResultsCountRenderer;

    /**
     * @var \Wyomind\ElasticsearchCore\Block\Adminhtml\System\Config\Form\Field\Renderer\ShowMoreLess
     */
    private $_showMoreLessRenderer;

    /**
     * @var Wyomind\ElasticsearchCore\Block\Adminhtml\System\Config\Form\Field\Renderer\ShowLayerFilter
     */
    private $_showLayerFilterRenderer;

    private $_noFollowRenderer;

    /**
     * Drag and drop renderer
     * @var \Magento\Framework\View\Element\Html\Link
     */
    private $_handleRenderer;

    /**
     * @var bool
     */
    protected $_addAfter = true;

    /**
     * @var string
     */
    protected $_addButtonLabel = '';

    /**
     * @var bool
     */
    protected $closed = true;
    protected $noFollow = true;
    protected $generateUrl = true;

    /**
     * Constructor
     */
    protected function _construct()
    {
        parent::_construct();
        $this->_addButtonLabel = __('Add an attribute');
    }

    /**
     * Get the filterable attribute renderer
     * @return \Wyomind\ElasticsearchCore\Block\Adminhtml\System\Config\Form\Field\Renderer\FilterableAttributes|\Magento\Framework\View\Element\BlockInterface
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function getFilterableAttributesRenderer()
    {
        if (!$this->_filterableAttributesRenderer) {
            $this->_filterableAttributesRenderer = $this->getLayout()->createBlock(
                '\Wyomind\ElasticsearchCore\Block\Adminhtml\System\Config\Form\Field\Renderer\FilterableAttributes', '', ['data' => ['is_render_to_js_template' => true]]
            );
        }
        return $this->_filterableAttributesRenderer;
    }

    /**
     * @return \Magento\Framework\View\Element\BlockInterface
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function getClosedRenderer()
    {
        if (!$this->_closedRenderer) {
            $this->_closedRenderer = $this->getLayout()->createBlock(
                '\Wyomind\ElasticsearchCore\Block\Adminhtml\System\Config\Form\Field\Renderer\Closed', '', ['data' => ['is_render_to_js_template' => true]]
            );
        }
        return $this->_closedRenderer;
    }

    /**
     * Get the "show results count" renderer
     * @return \Wyomind\ElasticsearchCore\Block\Adminhtml\System\Config\Form\Field\Renderer\ShowResultsCount|\Magento\Framework\View\Element\BlockInterface
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function getShowResultsCountRenderer()
    {
        if (!$this->_showResultsCountRenderer) {
            $this->_showResultsCountRenderer = $this->getLayout()->createBlock(
                '\Wyomind\ElasticsearchCore\Block\Adminhtml\System\Config\Form\Field\Renderer\ShowResultsCount', '', ['data' => ['is_render_to_js_template' => true]]
            );
        }
        return $this->_showResultsCountRenderer;
    }

    /**
     * @return \Magento\Framework\View\Element\BlockInterface|Renderer\ShowResultsCount
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function getShowMoreLessRenderer()
    {
        if (!$this->_showMoreLessRenderer) {
            $this->_showMoreLessRenderer = $this->getLayout()->createBlock(
                '\Wyomind\ElasticsearchCore\Block\Adminhtml\System\Config\Form\Field\Renderer\ShowMoreLess', '', ['data' => ['is_render_to_js_template' => true]]
            );
        }
        return $this->_showMoreLessRenderer;
    }

    /**
     * @return \Magento\Framework\View\Element\BlockInterface|Wyomind\ElasticsearchCore\Block\Adminhtml\System\Config\Form\Field\Renderer\ShowLayerFilter
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function getShowLayerFilterRenderer()
    {
        if (!$this->_showLayerFilterRenderer) {
            $this->_showLayerFilterRenderer = $this->getLayout()->createBlock(
                '\Wyomind\ElasticsearchCore\Block\Adminhtml\System\Config\Form\Field\Renderer\ShowLayerFilter', '', ['data' => ['is_render_to_js_template' => true]]
            );
        }
        return $this->_showLayerFilterRenderer;
    }

    /**
     * @return \Magento\Framework\View\Element\BlockInterface|Renderer\GenerateUrl
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function getGenerateUrlRenderer()
    {
        if (!$this->_generateUrlRenderer) {
            $this->_generateUrlRenderer = $this->getLayout()->createBlock(
                '\Wyomind\ElasticsearchCore\Block\Adminhtml\System\Config\Form\Field\Renderer\GenerateUrl', '', ['data' => ['is_render_to_js_template' => true]]
            );
        }
        return $this->_generateUrlRenderer;
    }


    protected function getNoFollowRenderer()
    {
        if (!$this->_noFollowRenderer) {
            $this->_noFollowRenderer = $this->getLayout()->createBlock(
                '\Wyomind\ElasticsearchCore\Block\Adminhtml\System\Config\Form\Field\Renderer\NoFollow', '', ['data' => ['is_render_to_js_template' => true]]
            );
        }
        return $this->_noFollowRenderer;
    }


    /**
     * Get the drag and drop renderer
     * @return \Magento\Framework\View\Element\BlockInterface|\Magento\Framework\View\Element\Html\Link
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function getHandleRenderer()
    {
        if (!$this->_handleRenderer) {
            $this->_handleRenderer = $this->getLayout()->createBlock(
                '\Magento\Framework\View\Element\Html\Link', '', ['data' => ['is_render_to_js_template' => true]]
            );
        }
        return $this->_handleRenderer;
    }

    /**
     * @{inheritdoc}
     */
    protected function _prepareToRender()
    {
        $this->addColumn(
            'handle', [
                'label' => ' ',
                'renderer' => $this->getHandleRenderer()
            ]
        );
        $this->addColumn(
            'position', [
                'label' => __('Position')
            ]
        );
        $this->addColumn(
            'attribute_code', [
                'label' => __('Filterable Attribute'),
                'renderer' => $this->getFilterableAttributesRenderer()
            ]
        );

        if ($this->closed) {
            $this->addColumn(
                'closed', [
                    'label' => __('Closed'),
                    'renderer' => $this->getClosedRenderer()
                ]
            );
        }

        $this->addColumn(
            'show_results_count', [
                'label' => __('Results count'),
                'renderer' => $this->getShowResultsCountRenderer()
            ]
        );
        $this->addColumn(
            'show_more_less', [
                'label' => __('Show More/Less'),
                'renderer' => $this->getShowMoreLessRenderer()
            ]
        );
        $this->addColumn(
            'show_more_less_nb_values', [
                'label' => __('Nb of values')
            ]
        );
        $this->addColumn(
            'show_layer_filter', [
                'label' => __('Input filter'),
                'renderer' => $this->getShowLayerFilterRenderer()
            ]
        );

        if ($this->generateUrl) {
            $this->addColumn(
                'generate_url', [
                    'label' => __('Update Browser Url'),
                    'renderer' => $this->getGenerateUrlRenderer()
                ]
            );
        }

        if ($this->noFollow) {
            $this->addColumn(
                'no_follow', [
                    'label' => __('No Follow'),
                    'renderer' => $this->getNoFollowRenderer()
                ]
            );
        }
        $this->_addAfter = false;
    }

    /**
     * @param \Magento\Framework\DataObject $row
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function _prepareArrayRow(\Magento\Framework\DataObject $row)
    {
        $attributeCode = $row->getAttributeCode();
        $options = [];
        if ($attributeCode) {
            $options['option_' . $this->getFilterableAttributesRenderer()->calcOptionHash($attributeCode)] = 'selected="selected"';
        }
        $closed = $row->getClosed();
        if ($closed == null) {
            $closed = 0;
        }
        $options['option_' . $this->getClosedRenderer()->calcOptionHash($closed)] = 'selected="selected"';

        $generateUrl = $row->getGenerateUrl();
        if ($generateUrl == null) {
            $generateUrl = 0;
        }
        $options['option_' . $this->getGenerateUrlRenderer()->calcOptionHash($generateUrl)] = 'selected="selected"';

        $showResultsCount = $row->getShowResultsCount();
        if ($showResultsCount == null) {
            $showResultsCount = 0;
        }
        $options['option_' . $this->getShowResultsCountRenderer()->calcOptionHash($showResultsCount)] = 'selected="selected"';

        $showLayerFilter = $row->getShowLayerFilter();
        if ($showLayerFilter == null) {
            $showLayerFilter = 0;
        }
        $options['option_' . $this->getShowLayerFilterRenderer()->calcOptionHash($showLayerFilter)] = 'selected="selected"';

        $showMoreLess = $row->getShowMoreLess();
        if ($showMoreLess == null) {
            $showMoreLess = 0;
        }
        $options['option_' . $this->getShowMoreLessRenderer()->calcOptionHash($showMoreLess)] = 'selected="selected"';

        $noFollow = $row->getNoFollow();
        if ($noFollow == null) {
            $noFollow = 0;
        }
        $options['option_' . $this->getNoFollowRenderer()->calcOptionHash($noFollow)] = 'selected="selected"';

        $row->setData('option_extra_attrs', $options);
    }

    /**
     * @param string $columnName
     * @return string
     * @throws \Exception
     */
    public function renderCellTemplate($columnName)
    {
        if ($columnName == 'position') {
            $this->_columns[$columnName]['class'] = 'input-text required-entry validate-number';
            $this->_columns[$columnName]['style'] = 'width:50px; display:none';
        }
        if ($columnName == 'show_more_less_nb_values') {
            $this->_columns[$columnName]['class'] = 'input-text required-entry validate-number';
            $this->_columns[$columnName]['style'] = 'width:50px;';
        }
        return parent::renderCellTemplate($columnName);
    }
}