<?php

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

use FiloBlu\Rma\Block\Adminhtml\Form\Field\CustomerGroupPolicyColumn;
use FiloBlu\Rma\Model\Config\Source\RmaCreationPolicies;
use Magento\Backend\Block\Template\Context;
use Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray;
use Magento\Customer\Model\ResourceModel\Group\CollectionFactory;
use Magento\Framework\DataObject;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\View\Element\Html\Select;


class MatrixRate extends AbstractFieldArray
{
    /**
     * @var
     */
    protected $returnType;

    protected $customerGroup;

    protected $returnCost;

    /**
     * @var CollectionFactory
     */
    protected $customerGroupCollectionFactory;
    /**
     * @var RmaCreationPolicies
     */
    protected $rmaCreationPolicy;

    /**
     * DynamicRow constructor.
     * @param Context $context
     * @param CollectionFactory $customerGroupCollectionFactory
     * @param RmaCreationPolicies $rmaCreationPolicy
     * @param array $data
     */
    public function __construct(
        Context $context,
        CollectionFactory $customerGroupCollectionFactory,
        RmaCreationPolicies $rmaCreationPolicy,
        array $data = []
    ) {
        $this->customerGroupCollectionFactory = $customerGroupCollectionFactory;
        parent::__construct($context, $data);
        $this->rmaCreationPolicy = $rmaCreationPolicy;
    }

    /**
     * Prepare rendering the new field by adding all the needed columns
     *
     * @throws LocalizedException
     */
    protected function _prepareToRender()
    {
        $this->addColumn(
            'return_type',
            [
                'label' => __('Matrix Rate'),
                'renderer' => $this->_getReturnTypeRenderer(),
            ]
        );
        $this->addColumn(
            'customer_group',
            [
                'label' => __('Customer Group'),
                'renderer' => $this->_getCustomerGroupRenderer()
            ]
        );
        $this->addColumn(
            'return_cost',
            [
                'label' => __('Return Cost'),
                'renderer' => $this->_getReturnCostRenderer(),
            ]
        );
        $this->_addAfter = false;
        $this->_addButtonLabel = __('Add Policy');
    }

    /**
     * Retrieve the renderer for the "return_type" field
     *
     * @return Select
     * @throws LocalizedException
     */
    protected function _getReturnTypeRenderer()
    {
        if (!$this->returnType) {
            $this->returnType = $this->getLayout()->createBlock(
                Select::class,
                '',
                ['data' => ['is_render_to_js_template' => true]]
            );
        }

        $options = $this->rmaCreationPolicy->toOptionArray();

        $this->returnType->setOptions($options);
        $this->returnType
            ->setId($this->_getCellInputElementId('<%- _id %>', 'return_type'))
            ->setName($this->_getCellInputElementName('return_type'));

        return $this->returnType;
    }

    /**
     * Retrieve the renderer for the "customer_group" field
     *
     * @return Select
     * @throws LocalizedException
     */
    protected function _getCustomerGroupRenderer()
    {
        if (!$this->customerGroup) {
            $this->customerGroup = $this->getLayout()->createBlock(
                CustomerGroupPolicyColumn::class,
                '',
                ['data' => ['is_render_to_js_template' => true]]
            );
        }

        $customerGroups = $this->customerGroupCollectionFactory->create()->toOptionArray();

        $this->customerGroup->setOptions($customerGroups);
        $this->customerGroup
            ->setId($this->_getCellInputElementId('<%- _id %>', 'customer_group'))
            ->setName($this->_getCellInputElementName('customer_group'));


        return $this->customerGroup;
    }

    /**
     * Retrieve the renderer for the "rma_cost" field
     *
     * @return Select
     * @throws LocalizedException
     */
    protected function _getReturnCostRenderer()
    {
        if (!$this->returnCost) {
            $this->returnCost = $this->getLayout()->createBlock(
                Select::class,
                '',
                ['data' => ['is_render_to_js_template' => true]]
            );
        }

        $options = [
            [
                'value' => 0,
                'label' => __('No')
            ],
            [
                'value' => 1,
                'label' => __('Yes')
            ]
        ];


        $this->returnCost->setOptions($options);
        $this->returnCost
            ->setId($this->_getCellInputElementId('<%- _id %>', 'return_cost'))
            ->setName($this->_getCellInputElementName('return_cost'));

        return $this->returnCost;
    }

    /**
     * Prepare existing row data object
     *
     * @param DataObject $row
     * @throws LocalizedException
     */
    protected function _prepareArrayRow(DataObject $row)
    {

        $returnType = $row->getData('return_type');
        $customerGroup = $row->getData('customer_group');
        $returnCost = $row->getData('return_cost');

        $options['option_' . $this->_getReturnTypeRenderer()->calcOptionHash($returnType)] = 'selected="selected"';

        if ($customerGroup) {
            foreach ($customerGroup as $group) {
                $options['option_' . $this->_getCustomerGroupRenderer()->calcOptionHash($group)] = 'selected="selected"';
            }
        }

        $options['option_' . $this->_getReturnCostRenderer()->calcOptionHash($returnCost)] = 'selected="selected"';

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