<?php

namespace FiloBlu\Storelocator\Block\Adminhtml\Stores\Edit\Tab;

use FiloBlu\Storelocator\Model\ResourceModel\Tags\Collection;
use FiloBlu\Storelocator\Model\ResourceModel\Tags\CollectionFactory;
use FiloBlu\Storelocator\Model\Stores;
use FiloBlu\Storelocator\Model\TagFactory;
use FiloBlu\Storelocator\Model\TagsFactory;
use Magento\Backend\Block\Template\Context;
use Magento\Backend\Block\Widget\Grid\Column;
use Magento\Backend\Block\Widget\Grid\Extended;
use Magento\Backend\Block\Widget\Tab\TabInterface;
use Magento\Backend\Helper\Data;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Registry;

/**
 *
 */
class Tag extends Extended implements TabInterface
{
    /**
     * Tag collection factory
     *
     * @var CollectionFactory
     */
    protected $tagCollectionFactory;

    /**
     * Registry
     *
     * @var Registry
     */
    protected $coreRegistry;

    /**
     * Tag factory
     *
     * @var TagFactory
     */
    protected $tagFactory;

    /**
     * @param CollectionFactory $eventsCollectionFactory
     * @param Registry $coreRegistry
     * @param TagsFactory $tagFactory
     * @param Context $context
     * @param Data $backendHelper
     * @param array $data
     */
    public function __construct(
        CollectionFactory $eventsCollectionFactory,
        Registry $coreRegistry,
        TagsFactory $tagFactory,
        Context $context,
        Data $backendHelper,
        array $data = []
    ) {
        $this->tagCollectionFactory = $eventsCollectionFactory;
        $this->coreRegistry = $coreRegistry;
        $this->tagFactory = $tagFactory;
        parent::__construct($context, $backendHelper, $data);
    }


    /**
     * Set grid params
     * @noinspection MagicMethodsValidityInspection
     */
    public function _construct()
    {
        parent::_construct();
        $this->setId('tag_grid');
        $this->setDefaultSort('name');
        $this->setDefaultDir('ASC');
        $this->setUseAjax(true);
        if ($this->getStore()->getStoreId()) {
            $this->setDefaultFilter(['in_tags' => 1]);
        }
    }

    /**
     * @return Stores
     */
    public function getStore()
    {
        return $this->coreRegistry->registry('storelocator_store');
    }

    /**
     * Retrieve selected Tags
     * @return array
     */
    public function getSelectedTags()
    {
        return $this->getStore()->getOldTags();
    }

    /**
     * @param $item
     * @return string
     */
    public function getRowUrl($item)
    {
        return '#';
    }

    /**
     * get grid url
     *
     * @return string
     */
    public function getGridUrl()
    {
        return $this->getUrl(
            '*/*/tagsGrid',
            [
                'store_id' => $this->getStore()->getStoreId()
            ]
        );
    }

    /**
     * @return bool
     */
    public function isHidden()
    {
        return false;
    }

    /**
     * @return string
     */
    public function getTabTitle()
    {
        return $this->getTabLabel();
    }

    /**
     * @return string
     */
    public function getTabLabel()
    {
        return __('Tags');
    }

    /**
     * @return bool
     */
    public function canShowTab()
    {
        return true;
    }

    /**
     * @return string
     */
    public function getTabUrl()
    {
        return $this->getUrl('filoblustorelocatoradmin/stores/tags', ['_current' => true]);
    }

    /**
     * @return string
     */
    public function getTabClass()
    {
        return 'ajax only';
    }

    /**
     * prepare the collection
     * @return $this
     */
    protected function _prepareCollection()
    {
        /** @var Collection $collection */
        $collection = $this->tagCollectionFactory->create();

        if ($this->getStore()->getStoreId()) {
            $constraint = 'related.store_id=' . $this->getStore()->getStoreId();
        } else {
            $constraint = 'related.store_id=0';
        }
        $collection->getSelect()->joinLeft(
            ['related' => $collection->getTable('filoblu_storelocator_store_tag')],
            'related.tag_id=main_table.tag_id AND ' . $constraint,
            ['store_id']
        );

        $this->setCollection($collection);
        parent::_prepareCollection();
        return $this;
    }

    /**
     * @return $this
     */
    protected function _prepareMassaction()
    {
        return $this;
    }

    /**
     * @return $this
     * @throws \Exception
     */
    protected function _prepareColumns()
    {
        $this->addColumn(
            'in_tags',
            [
                'header_css_class' => 'a-center',
                'type'             => 'checkbox',
                'name'             => 'in_tag',
                'values'           => $this->_getSelectedTags(),
                'align'            => 'center',
                'index'            => 'tag_id'
            ]
        );
        $this->addColumn(
            'tag_id',
            [
                'header'           => __('ID'),
                'sortable'         => true,
                'index'            => 'tag_id',
                'type'             => 'number',
                'header_css_class' => 'col-id',
                'column_css_class' => 'col-id'
            ]
        );

        $this->addColumn(
            'tag_name',
            [
                'header'           => __('Name'),
                'index'            => 'name',
                'header_css_class' => 'col-name',
                'column_css_class' => 'col-name'
            ]
        );

        $this->addColumn(
            'tag_image',
            [
                'header'   => __('Image'),
                'index'    => 'image',
                'renderer' => \FiloBlu\Storelocator\Block\Adminhtml\Stores\Grid\Renderer\Tag\Image::class,
            ]
        );

        return $this;
    }

    /**
     * Retrieve selected Tags
     * @return array
     */
    protected function _getSelectedTags()
    {
        $tags = $this->getStoreTags();

        if (!is_array($tags)) {
            return $this->getStore()->getOldTags();
        }

        return $tags;
    }

    /**
     * @param Column $column
     * @return $this
     * @throws LocalizedException
     */
    protected function _addColumnFilterToCollection($column)
    {
        if ($column->getId() == 'in_tags') {
            $tagIds = $this->_getSelectedTags();

            if (empty($tagIds)) {
                $tagIds = 0;
            }

            if ($column->getFilter()->getValue()) {
                $this->getCollection()->addFieldToFilter('main_table.tag_id', ['in' => $tagIds]);
                $this->getCollection()->addFieldToFilter('main_table.tag_id', ['in' => $tagIds]);
            } else {
                if ($tagIds) {
                    $this->getCollection()->addFieldToFilter('main_table.tag_id', ['nin' => $tagIds]);
                }
            }
        } else {
            parent::_addColumnFilterToCollection($column);
        }

        return $this;
    }
}
