<?php

namespace FiloBlu\Flow\Block\Adminhtml\Inboundflow\Edit\Tab;

use Magento\Backend\Block\Template\Context;
use Magento\Backend\Block\Widget\Grid\Extended;
use Magento\Backend\Helper\Data;
use Magento\Catalog\Model\Product;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\App\ResourceConnection;
use Magento\Framework\DataObject;
use Magento\Framework\Exception\FileSystemException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Store\Api\Data\StoreInterface;

/**
 * Class Grid
 * @package FiloBlu\Flow\Block\Adminhtml\Inboundflow\Edit\Tab
 */
class Grid extends Extended
{
    /**
     * @var
     */
    protected $_collectionFactory;

    /**
     * @var
     */
    protected $_request;

    /**
     * @var
     */
    protected $_columnsFactory;

    /**
     * @param Context $context
     * @param Data $backendHelper
     * @param array $data
     *
     * @SuppressWarnings(PHPMD.ExcessiveParameterList)
     */
    public function __construct(
        Context $context,
        Data    $backendHelper,
        array   $data = []
    )
    {
        parent::__construct($context, $backendHelper, $data);
        $this->_request = $context->getRequest();
        $flow = urldecode($this->_request->getParam('flow', 0));
        $collection = ObjectManager::getInstance()->create("\FiloBlu\Flow\Model\ResourceModel\\{$flow}\Collection");
        $collection->addFieldToFilter('meta_file', $this->_getId());
        $this->setCollection($collection);
    }

    /**
     * @return int
     */
    protected function _getId()
    {
        return (int)$this->getRequest()->getParam('id', 0);
    }

    /**
     * @return string
     */
    public function getGridUrl()
    {
        return $this->getUrl('*/*/grid', ['_current' => true, 'id' => (int)$this->getRequest()->getParam('id', 0), 'flow' => $this->getRequest()->getParam('flow', 0)]);
    }

    /**
     * @param Product|DataObject $item
     * @return string
     */
    public function getRowUrl($item)
    {
        return 'javascript:void(0)';
    }

    /**
     * @return void
     * @throws FileSystemException
     */
    protected function _construct()
    {
        parent::_construct();

        $this->setId('flowGrid');
        $this->setDefaultSort('id');
        $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);
    }

    /**
     * @return StoreInterface
     * @throws NoSuchEntityException
     */
    protected function _getStore()
    {
        $storeId = (int)$this->getRequest()->getParam('store', 0);
        return $this->_storeManager->getStore($storeId);
    }

    /**
     * @return Extended
     * @throws LocalizedException
     */
    protected function _prepareColumns()
    {
        $this->addColumn(
            'meta_id',
            [
                'header' => __('Meta Id'),
                'index'  => 'meta_id',
                'class'  => 'id'
            ]
        );

        $this->addColumn(
            'meta_processed',
            [
                'header' => __('Processed'),
                'index'  => 'meta_processed'
            ]
        );

        $columns = $this->getTableData();

        foreach ($columns as $column) {
            if ($column['COLUMN_NAME'] === 'meta_id' || $column['COLUMN_NAME'] === 'meta_processed') {
                continue;
            }

            $this->addColumn(
                $column['COLUMN_NAME'],
                [
                    'header' => __($column['COLUMN_NAME']),
                    'type'   => $column['DATA_TYPE'],
                    'index'  => $column['COLUMN_NAME'],

                ]
            );
        }

        $block = $this->getLayout()->getBlock('grid.bottom.links');
        if ($block) {
            $this->setChild('grid.bottom.links', $block);
        }

        return parent::_prepareColumns();
    }

    /**
     * @return mixed
     */
    protected function getTableData()
    {
        $connection = $this->getCollection()->getResource()->getConnection(ResourceConnection::DEFAULT_CONNECTION);
        $mainTable = $this->getCollection()->getResource()->getMainTable();
        $this->_columnsFactory = $connection->describeTable($mainTable);
        return $this->_columnsFactory;
    }
}
