<?php

namespace FiloBlu\ExtBlackbirdMenuManager\Block\Adminhtml\Subcategory\Widget;

use Blackbird\MenuManager\Block\Adminhtml\Widget\Chooser\AbstractChooser;
use Magento\Backend\Block\Template\Context;
use Magento\Backend\Block\Widget\Grid\Column;
use Magento\Backend\Helper\Data;
use Magento\Catalog\Model\Config\Source\Category;
use Magento\Catalog\Model\ResourceModel\Category\CollectionFactory;
use Magento\Config\Model\Config\Source\Enabledisable;
use Magento\Framework\Data\Form\Element\AbstractElement;

/**
 *
 */
class Chooser extends AbstractChooser
{
    /**
     * @var \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory
     */
    protected $categoryCollectionFactory;

    /**
     * @var \Magento\Catalog\Model\Config\Source\Category
     */
    protected $categoryTypesSource;

    /**
     * @var
     */
    protected $enableDisable;

    /**
     * Chooser constructor.
     * @param \Magento\Backend\Block\Template\Context $context
     * @param \Magento\Backend\Helper\Data $backendHelper
     * @param \Magento\Catalog\Model\ResourceModel\Category\CollectionFactory $categoryCollectionFactory
     * @param \Magento\Catalog\Model\Config\Source\Category $categoryTypesSource
     * @param \Magento\Config\Model\Config\Source\Enabledisable $enableDisable
     * @param array $data
     */
    public function __construct(
        Context $context,
        Data $backendHelper,
        CollectionFactory $categoryCollectionFactory,
        Category $categoryTypesSource,
        Enabledisable $enableDisable,
        array $data = []
    ) {
        $this->categoryCollectionFactory = $categoryCollectionFactory;
        $this->categoryTypesSource = $categoryTypesSource;
        $this->enableDisable = $enableDisable;
        parent::__construct($context, $backendHelper, $data);
    }

    /**
     * Prepare chooser element HTML
     *
     * @param AbstractElement $element Form Element
     * @return AbstractElement
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    public function prepareElementHtml(AbstractElement $element)
    {
        $uniqId = $this->mathRandom->getUniqueHash($element->getId());
        $sourceUrl = $this->getUrl(
            'menumanager/category_widget/chooser',
            ['uniq_id' => $uniqId]
        );

        $chooser = $this->getLayout()->createBlock(
            Chooser::class
        )->setElement(
            $element
        )->setConfig(
            $this->getConfig()
        )->setFieldsetId(
            $this->getFieldsetId()
        )->setSourceUrl(
            $sourceUrl
        )->setUniqId(
            $uniqId
        );

        $element->setData('after_element_html', $chooser->toHtml());
        return $element;
    }

    /**
     * Get grid url
     *
     * @return string
     */
    public function getGridUrl()
    {
        return $this->getUrl(
            'menumanager/category_widget/chooser',
            [
                '_current'       => true,
                'uniq_id'        => $this->getId(),
                'use_massaction' => $this->getUseMassaction(),
            ]
        );
    }

    /**
     * @param $item
     * @return array
     */
    public function getMultipleRows($item)
    {
        return [];
    }

    /**
     * Block construction, prepare grid params
     *
     * @return void
     * @throws \Magento\Framework\Exception\FileSystemException
     * @noinspection MagicMethodsValidityInspection
     */
    protected function _construct()
    {
        parent::_construct();
        $this->setDefaultSort('title');
        $this->setUseAjax(true);
        $this->setDefaultFilter(['chooser_is_active' => '1']);

        if ($form = $this->getJsFormObject()) {
            $this->setRowInitCallback("{$form}.chooserGridRowInit.bind({$form})");
        }
    }

    /**
     * Filter checked/unchecked rows in grid
     *
     * @param Column $column
     * @return $this
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function _addColumnFilterToCollection($column)
    {
        if ($column->getId() === 'in_categories') {
            $selected = $this->getSelectedEntities();
            if ($column->getFilter()->getValue()) {
                $this->getCollection()->addFieldToFilter('entity_id', ['in' => $selected]);
            } else {
                $this->getCollection()->addFieldToFilter('entity_id', ['nin' => $selected]);
            }
        } else {
            parent::_addColumnFilterToCollection($column);
        }
        return $this;
    }

    /**
     * Prepare category collection
     *
     * @return $this
     * @throws \Magento\Framework\Exception\LocalizedException
     */
    protected function _prepareCollection()
    {
        $collection = $this->categoryCollectionFactory->create()->addAttributeToSelect('*');

        $this->setCollection($collection);

        return parent::_prepareCollection();
    }

    /**
     * Prepare columns for pages grid
     *
     * @return $this
     * @throws \Exception
     */
    protected function _prepareColumns()
    {
        $this->addColumn(
            'in_categories',
            [
                'header_css_class' => 'a-center',
                'type'             => 'checkbox',
                'name'             => 'in_categories',
                'inline_css'       => 'checkbox entities',
                'field_name'       => 'in_categories',
                'values'           => $this->getSelectedEntities(),
                'align'            => 'center',
                'index'            => 'entity_id',
                'use_index'        => true
            ]
        );

        $this->addColumn(
            'entity_id',
            [
                'header'           => __('ID'),
                'index'            => 'entity_id',
                'header_css_class' => 'col-id',
                'column_css_class' => 'col-id'
            ]
        );

        $this->addColumn(
            'categoryName',
            [
                'header'           => __('Category Name'),
                'index'            => 'name',
                'header_css_class' => 'col-categoryName',
                'column_css_class' => 'col-categoryName'
            ]
        );
        $this->addColumn(
            'categoryParent',
            [
                'header'           => __('Parent Category'),
                'index'            => 'parent_id',
                'header_css_class' => 'col-categoryParent',
                'column_css_class' => 'col-categoryParent'
            ]
        );

        return parent::_prepareColumns();
    }

    /**
     * Convet an array to options
     *
     * @param array $array
     * @return array
     */
    protected function toOptions(array $array)
    {
        $options = [];

        foreach ($array as $line) {
            $options[$line['value']] = $line['label'];
        }

        return $options;
    }
}
