<?php

declare(strict_types=1);

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

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

use function is_array;

/**
 *
 */
class CspRules extends AbstractFieldArray
{
    /**
     * @var bool
     */
    protected $_addAfter = false;

    /**
     * @var string
     */
    protected $_template = 'FiloBlu_Refilo::system/config/form/field/array.phtml';

    /**
     * Obtain existing data from form element
     *
     * Each row will be instance of \Magento\Framework\DataObject
     *
     * @return array
     */
    public function getArrayRows()
    {
        $element = $this->getElement();

        if (!$element->getValue() || !is_array($element->getValue())) {
            $element->setValue([
                uniqid('_', true) => ['rule' => 'google-analytics', 'enabled' => false],
                uniqid('_', true) => ['rule' => 'google-tag-manager', 'enabled' => false],
                uniqid('_', true) => ['rule' => 'google-recaptcha', 'enabled' => false],
                uniqid('_', true) => ['rule' => 'zendesk', 'enabled' => false],
                uniqid('_', true) => ['rule' => 'polyfill', 'enabled' => false],
                uniqid('_', true) => ['rule' => 'filoblu', 'enabled' => false],
            ]);
        }

        return parent::getArrayRows();
    }

    /**
     * Prepare rendering the new field by adding all the needed columns
     */
    protected function _prepareToRender()
    {
        $this->addColumn(
            'rule',
            [
                'label'    => __('Application'),
                'renderer' => $this->getLayout()->createBlock(TextColumn::class)
            ]
        );
        $this->addColumn(
            'enabled',
            [
                'enabled'  => __('Enabled'),
                'renderer' => $this->getLayout()->createBlock(BooleanColumn::class)
            ]
        );
    }
}
