<?php

namespace FiloBlu\Flow\Block\Adminhtml\System\Config;

use FiloBlu\Flow\Model\ResourceModel\Channel\Collection;
use Magento\Backend\Block\Template\Context;
use Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray;
use Magento\Framework\DataObject;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\View\Element\Html\Select;
use Magento\Store\Model\ResourceModel\Website\CollectionFactory;

class MappingFields extends AbstractFieldArray
{

    /**
     * @var CollectionFactory
     */
    protected $_websitesCollection;
    /**
     * @var Collection
     */
    protected $_channelCollection;
    /**
     * @var null
     */
    protected $_websitesRenderer;

    /**
     * MappingFields constructor.
     * @param Context $context
     * @param CollectionFactory $collection
     * @param Collection $channel_collection
     * @param array $data
     */
    public function __construct(
        Context $context,
        CollectionFactory $collection,
        Collection $channel_collection,
        array $data = []
    ) {
        $this->_websitesCollection = $collection;
        $this->_channelCollection = $channel_collection;
        parent::__construct($context, $data);
    }

    /**
     * @return array
     */
    protected function getChannelOptions()
    {
        $options = [];
        foreach ($this->_channelCollection as $channel) {
            $channel_data = json_decode($channel->getData('data'));
            if ($channel_data && $channel_data->config && $channel_data->config->flow === "From\\Product") {
                $options[] = [
                    'value' => $channel->getName(),
                    'label' => $channel->getName()
                ];
            }
        }

        return $options;
    }

    /**
     * @throws LocalizedException
     */
    protected function _prepareToRender()
    {
        $channel_options = $this->getChannelOptions();
        array_unshift($channel_options, ['value' => '', 'label' => __('-- Select --')]);

        $channelBlock = $this->getLayout()->createBlock(Select::class)
            ->setId($this->_getCellInputElementId('<%- _id %>', 'channel'))
            ->setName($this->_getCellInputElementName('channel'))
            ->setClass('select')
            ->setOptions($channel_options);

        $this->addColumn('channel', [
            'label' => __('Masterfile'),
            'renderer' => $channelBlock
        ]);

        $websitesBlock=$this->getWebsitesRenderer();
        $this->addColumn('website_id', [
            'label' => __('Website'),
            'renderer' => $websitesBlock
        ]);

        $this->_addButtonLabel = __('Add');
    }

    /**
     * @param DataObject $row
     * @throws LocalizedException
     */
    protected function _prepareArrayRow(DataObject $row)
    {
        $renderer=  $this->getWebsitesRenderer();

        $column_values=$row->getColumnValues();
        unset($column_values[$row->getData('_id') . '_website_id']);
        $row->setData('column_values', $column_values);

        //Set selected values for multiselect using option_extra_attrs
        $websites = $row->getWebsite_id();
        if ($websites) {
            $options = [];
            foreach ($websites as $website) {
                $options['option_' . $renderer->calcOptionHash($website)]
                    = 'selected="selected"';
            }
            $row->setData('option_extra_attrs', $options);
        }
    }

    /**
     * @return null
     * @throws LocalizedException
     */
    protected function getWebsitesRenderer()
    {
        if (!$this->_websitesRenderer) {
            $websites_options = $this->_websitesCollection->create()->toOptionArray();
            array_unshift($websites_options, ['value' => '', 'label' => __('-- Select --')]);

            $this->_websitesRenderer = $this->getLayout()->createBlock(
                Select::class,
                '',
                ['data' => ['is_render_to_js_template' => true]]
            )
                ->setId($this->_getCellInputElementId('<%- _id %>', 'website_id'))
                ->setName($this->_getCellInputElementName('website_id') . '[]')
                ->setClass('multiselect')
                ->setOptions($websites_options)
                ->setExtraParams('style="width:160px" multiple="multiple" size="5" ');
        }
        return $this->_websitesRenderer;
    }
}
