<?php
/**
 * @module  Autogedal_SeoCanonical
 * @author  Autogedal
 * @licence OSL 3.0
 */

namespace Autogedal\SeoCanonical\Block\Adminhtml\Form\Field;

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

class CategoryConfig extends AbstractFieldArray
{
    /**
     * @var AttributeColumn
     */
    private $attributeRenderer;

    /**
     * Prepare rendering the new field by adding all the needed columns
     */
    protected function _prepareToRender()
    {
        $this->addColumn('category_id', [
            'label' => __('Category ID'),
            'class' => 'required-entry validate-digits'
        ]);

        $this->addColumn('marca_attribute', [
            'label' => __('Marca Attribute'),
            'renderer' => $this->getAttributeRenderer()
        ]);

        $this->addColumn('model_attribute', [
            'label' => __('Model Attribute'),
            'renderer' => $this->getAttributeRenderer()
        ]);

        $this->addColumn('caroserie_attribute', [
            'label' => __('Caroserie Attribute'),
            'renderer' => $this->getAttributeRenderer()
        ]);

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

    /**
     * Prepare existing row data object
     *
     * @param DataObject $row
     * @throws LocalizedException
     */
    protected function _prepareArrayRow(DataObject $row): void
    {
        $options = [];

        $marcaAttribute = $row->getMarcaAttribute();
        if ($marcaAttribute !== null) {
            $options['option_' . $this->getAttributeRenderer()->calcOptionHash($marcaAttribute)] = 'selected="selected"';
        }

        $modelAttribute = $row->getModelAttribute();
        if ($modelAttribute !== null) {
            $options['option_' . $this->getAttributeRenderer()->calcOptionHash($modelAttribute)] = 'selected="selected"';
        }

        $caroserieAttribute = $row->getCaroserieAttribute();
        if ($caroserieAttribute !== null) {
            $options['option_' . $this->getAttributeRenderer()->calcOptionHash($caroserieAttribute)] = 'selected="selected"';
        }

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

    /**
     * Get the attribute renderer
     *
     * @return AttributeColumn
     * @throws LocalizedException
     */
    private function getAttributeRenderer()
    {
        if (!$this->attributeRenderer) {
            $this->attributeRenderer = $this->getLayout()->createBlock(
                AttributeColumn::class,
                '',
                ['data' => ['is_render_to_js_template' => true]]
            );
        }
        return $this->attributeRenderer;
    }
}
