<?php

namespace Nublue\CountdownTimer\Block\Adminhtml\System\Config\Form\Field;

class skipDays extends \Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray
{
    /**
     * Rows cache
     * @var array|null
     */
    protected $_arrayDirectoryCache;
    
    /**
     * @var \Nublue\CountdownTimer\Block\Adminhtml\System\Config\DateField
     */
    protected $_dateRenderer;
    
    
    /**
     * {@inheritdoc}
     */
    protected function _prepareToRender() {
        $this->addColumn('Name', ['label' => __('Name')]);
        $this->addColumn('Date', ['label' => __('Date'), 'format' => 'dd-mm-yy', 'input_format' => 'dd-mm-yy', 'renderer' => $this->_getDateColumnRenderer()]);
        $this->_addAfter = false;
        $this->_addButtonLabel = __('Add');
        parent::_construct();
    }

    /**
     * 
     */
    protected function _getDateColumnRenderer() {
        if( !$this->_dateRenderer ) {
            $this->_dateRenderer = $this->getLayout()->createBlock(
                'Nublue\CountdownTimer\Block\Adminhtml\System\Config\DateField',
                '',
                [
                    'data' => [
                        'is_render_to_js_template' => true,
                        'date_format'              => 'dd-mm-Y'
                    ]
                ]
            );
        }

        return $this->_dateRenderer;
    }
    
    /**
     * {@inheritdoc}
     */
    public function getArrayRows()
    {
        if (null !== $this->_arrayDirectoryCache) {
            return $this->_arrayDirectoryCache;
        }
        $result = [];
        $element = $this->getElement();
        $value = json_decode($element->getValue());
        if ($value !== null) {
            foreach ($value as $key) {
                $id = uniqid();
                $row = [
                    "Name" => $key->Name,
                    "Date" => $key->Date,
                    "_id" => $id,
                    "column_values" => [
                        $id . "_Name" => $key->Name,
                        $id . "_Date" => $key->Date
                    ]
                ];
                $result[$id] = new \Magento\Framework\DataObject($row);
                $this->_prepareArrayRow($result[$id]);
            }
        }
        $this->_arrayDirectoryCache = $result;
        return $this->_arrayDirectoryCache;
    }
}
