<?php
/**
 * Copyright © 2016 Filoblu S.r.l. All rights reserved.
 */

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

/**
 * Renderer for Event Configuration
 */

class Events extends \Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray
{
    
    /**
     * @var \Magento\Sales\Model\ResourceModel\Order\Status\Collection
     */
    protected $collection;

    /**
     * Statuses per state array
     *
     * @var array
     */
    protected $stateStatuses;

    /**
     * @var array
     */
    private $statuses;

    /**
     * @var Status
     */
    protected $orderStatusFactory;

    /**
     * @var \Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory
     */
    protected $orderStatusCollectionFactory;

    /**
     * @var \Magento\Payment\Api\PaymentMethodListInterface
     */
    protected $methodList;

    /**
     * @var Payment Methods
     */
    protected $paymentMethodRenderer = null;

    /**
     * Events constructor.
     * @param \Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory $orderStatusCollectionFactory
     * @param \Magento\Payment\Api\PaymentMethodListInterface $methodList
     * @param \Magento\Backend\Block\Template\Context $context
     * @param array $data
     */
    public function __construct(        
        \Magento\Sales\Model\ResourceModel\Order\Status\CollectionFactory $orderStatusCollectionFactory,
        \Magento\Payment\Api\PaymentMethodListInterface $methodList,
        \Magento\Backend\Block\Template\Context $context, 
        array $data = []
    ) {
        $this->orderStatusCollectionFactory = $orderStatusCollectionFactory;
        $this->methodList=$methodList;
        parent::__construct($context, $data);
    }

    /**
     * Enable the "Add after" button or not
     *
     * @var bool
     */
    protected $_addAfter = true;

    /**
     * Rows cache
     *
     * @var array|null
     */
    private $_arrayRowsCache;

    /**
     * Prepare to render
     *
     * @return void
     */
    protected function _prepareToRender()
    {
               
        $eventTypeBlock=$this->getLayout()->createBlock('Magento\Framework\View\Element\Html\Select')
                        ->setId($this->_getCellInputElementId('<%- _id %>','event_type'))
                        ->setName($this->_getCellInputElementName('event_type'))
                        ->setClass('select')
                        ->setOptions(
                            array(
                                ['value' => '', 'label' => __('-- Please Select --')],
                                ['value' => 'order_place', 'label' => __('Place Order')],
                                ['value' => 'invoice_register', 'label' => __('Invoice Register')],
                                ['value' => 'order_status', 'label' => __('Order Status Update')],
                                ['value' => 'create_shipment', 'label' => __('Create Shipment')]
                            )
                        );
        
        $this->addColumn('event_type', array(
            'label' => __('Event Type'),
            'renderer' => $eventTypeBlock
        ));
        $statuses = $this->orderStatusCollectionFactory->create()->toOptionHash();            
        array_unshift($statuses,  array('value' => '*', 'label' => __('-- Any --')));            

        $fromstatusesBlock=$this->getLayout()->createBlock('Magento\Framework\View\Element\Html\Select')
                        ->setId($this->_getCellInputElementId('<%- _id %>','from_status'))
                        ->setName($this->_getCellInputElementName('from_status'))
                        ->setClass('select')
                        ->setOptions($statuses);

        $this->addColumn('from_status', array(
            'label' => __('From Status'),
            'renderer' => $fromstatusesBlock
        ));

        $tostatusesBlock=$this->getLayout()->createBlock('Magento\Framework\View\Element\Html\Select')
                        ->setId($this->_getCellInputElementId('<%- _id %>','to_status'))
                        ->setName($this->_getCellInputElementName('to_status'))
                        ->setClass('select')
                        ->setOptions($statuses);

        $this->addColumn('to_status', array(
            'label' => __('To Status'),
            'renderer' => $tostatusesBlock
        ));

       
        $paymentMethodBlock=$this->getPaymentMethodRenderer();

        $this->addColumn('payment_methods', array(
            'label' => __('Payment Methods'),
            'renderer' => $paymentMethodBlock
        ));

        $this->addColumn('event_endpoint', array(
            'label' => __('Event Endpoint')

        ));

        $statuses = $this->orderStatusCollectionFactory->create()->toOptionHash();            
        array_unshift($statuses,  array('value' => '*', 'label' => __('-- No change --')));     
        $finalstatusesBlock=$this->getLayout()->createBlock('Magento\Framework\View\Element\Html\Select')
                        ->setId($this->_getCellInputElementId('<%- _id %>','final_status'))
                        ->setName($this->_getCellInputElementName('final_status'))
                        ->setClass('select')
                        ->setOptions($statuses);

        $this->addColumn('final_status', array(
            'label' => __('Final Status'),
            'renderer' => $finalstatusesBlock
        ));

        $this->addColumn('priority', array(
            'label' => __('Priority')
        ));

        $this->_addAfter = false;
        $this->_addButtonLabel = __('Add new event');
    }
 
    protected function _prepareArrayRow(\Magento\Framework\DataObject $row)
    {
        $renderer=  $this->getPaymentMethodRenderer();
        
        //The phtml set the value of DOM element by doing a $().value
        //This does not work with array values. Therefore we remove the values from column_value array. 
        //The values is set by "option_extra_attrs" set in the following.
        $column_values=$row->getColumnValues();   
        unset($column_values[$row->getData("_id")."_payment_methods"]);
        $row->setData("column_values", $column_values);
        
        //Set selected values for multiselect using option_extra_attrs
        $payment_methods = $row->getPaymentMethods();
        if($payment_methods){
            $options = [];
            foreach ($payment_methods as $payment_method) {
                $options['option_' . $renderer->calcOptionHash($payment_method)]
                    = 'selected="selected"';
            }
            $row->setData('option_extra_attrs', $options);  
        }
        //error_log(print_r($row,true),3, "/var/www/html/var/log/debug_event.log");
    }
 
    protected function getPaymentMethodRenderer()
    {
        if (!$this->paymentMethodRenderer) {
            $paymentMethodObjects=$this->methodList->getList(0);
            $paymentMethods=array(array('value' => '*', 'label' =>  __('-- Any --')));
            foreach($paymentMethodObjects as $paymentObject){
                array_push($paymentMethods, array("value" => $paymentObject->getCode(), "label" => $paymentObject->getCode()));
            }
            $this->paymentMethodRenderer = $this->getLayout()->createBlock(
                    'Magento\Framework\View\Element\Html\Select', 
                    '', 
                    ['data' => ['is_render_to_js_template' => true]]
                )
                ->setId($this->_getCellInputElementId('<%- _id %>','payment_methods'))
                ->setName($this->_getCellInputElementName('payment_methods')."[]")
                ->setClass('multiselect')   
                ->setOptions($paymentMethods)         
                ->setExtraParams('style="width:100px" multiple="multiple" size="5" ');
            
        }
        return $this->paymentMethodRenderer;
    }
 
}
