<?php

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

use Exception;
use FiloBlu\Refilo\Block\Adminhtml\System\Config\Form\Field\SelectPage;
use Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray;
use Magento\Framework\DataObject;
use Magento\Framework\Exception\LocalizedException;

/**
 * Class PaginationMapping
 * @package FiloBlu\Refilo\Block\Adminhtml\System\Config
 */
class PaginationMapping extends AbstractFieldArray
{

    /**
     * Grid columns
     *
     * @var array
     */
    protected $_columns = [];
    /**
     * @var
     */
    protected $_pageRenderer;
    /**
     * Enable the "Add after" button or not
     *
     * @var bool
     */
    protected $_addAfter = true;
    /**
     * Label of add button
     *
     * @var string
     */
    protected $_addButtonLabel;

    /**
     * Render array cell for prototypeJS template
     *
     * @param string $columnName
     * @return string
     * @throws Exception
     */
    public function renderCellTemplate($columnName)
    {
        if ($columnName === 'mode') {
            $this->_columns[$columnName]['style'] = 'width:100px;';
        }
        return parent::renderCellTemplate($columnName);
    }

    /**
     * Check if columns are defined, set template
     *
     * @return void
     */
    protected function _construct()
    {
        parent::_construct();
        $this->_addButtonLabel = __('Add');
    }

    /**
     * Prepare to render
     *
     * @return void
     * @throws LocalizedException
     */
    protected function _prepareToRender()
    {
        $this->addColumn('page', [
            'label' => __('Page'),
            'renderer' => $this->getPageRenderer('page'),
        ]);

        $this->addColumn('productnumber', [
            'label' => __('Product N.'),
            'style' => 'max-width: 50px;',
        ]);

        $this->addColumn('categoryids', [
            'label' => __('Category Ids'),
            'style' => 'max-width: 400px;',
        ]);

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

    /**
     * @return mixed
     * @throws LocalizedException
     */
    protected function getPageRenderer()
    {
        if (!$this->_pageRenderer) {
            $this->_pageRenderer = $this->getLayout()->createBlock(
                SelectPage::class,
                '',
                ['data' => ['is_render_to_js_template' => true]]
            );
        }
        return $this->_pageRenderer;
    }

    /**
     * @param DataObject $row
     * @throws LocalizedException
     */
    protected function _prepareArrayRow(DataObject $row)
    {
        $page = $row->getPage();
        $options = [];
        $options['option_' . $this->getPageRenderer()->calcOptionHash($page)] = 'selected="selected"';

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