<?php

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

use Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray;
use Magento\Framework\DataObject;

/**
 *
 */
class CountryUrl extends AbstractFieldArray
{

    /**
     * @var \FiloBlu\Refilo\Block\Adminhtml\System\Config\Form\Field\Country
     */
    protected $countryRenderer;

    /**
     * @return void
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function _prepareToRender()
    {
        $this->addColumn(
            'country_url',
            [
                'label'     => __('Country'),
                'renderer'  => $this->getCountryRenderer(),
            ]
        );
        $this->addColumn(
            'url_mapping',
            [
                'label' => __('Url')
            ]
        );
        $this->_addAfter = false;
    }

    /**
     * Returns renderer for country element
     *
     * @return \FiloBlu\Refilo\Block\Adminhtml\System\Config\Form\Field\Country
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function getCountryRenderer()
    {
        if (!$this->countryRenderer) {
            $this->countryRenderer = $this->getLayout()->createBlock(
                Country::class,
                '',
                ['data' => ['is_render_to_js_template' => true]]
            );
        }
        return $this->countryRenderer;
    }


    protected function _prepareArrayRow(DataObject $row)
    {
        $countries = $row->getCountryUrl();
        $options = [];
        if ($countries) {
            $countries = explode(',', $countries);
            foreach ($countries as $country) {
                $options['option_' . $this->getCountryRenderer()->calcOptionHash($country)]
                    = 'selected="selected"';
            }
        }
        $row->setData('option_extra_attrs', $options);
    }
}
