<?php

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

use Exception;
use FiloBlu\Storelocator\Model\ImageFactory;
use FiloBlu\Storelocator\Model\ImagesFactory;
use FiloBlu\Storelocator\Model\ResourceModel\Images\Collection;
use FiloBlu\Storelocator\Model\ResourceModel\Images\CollectionFactory;
use FiloBlu\Storelocator\Model\Stores;
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 Image extends Extended implements TabInterface
{
    /**
     * Image collection factory
     *
     * @var CollectionFactory
     */
    protected $imageCollectionFactory;

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

    /**
     * Image factory
     *
     * @var ImagesFactory
     */
    protected $imageFactory;

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


    /**
     * Set grid params
     */
    public function _construct()
    {
        parent::_construct();
        $this->setId('image_grid');
        $this->setDefaultSort('position');
        $this->setDefaultDir('ASC');
        $this->setUseAjax(true);
        if ($this->getStore()->getStoreId()) {
            $this->setDefaultFilter(['in_images' => 1]);
        }
    }

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

    /**
     * Retrieve selected Images
     * @return array
     */
    public function getSelectedImages()
    {
        $selected = $this->getStore()->getImagesPosition();
        if (!is_array($selected)) {
            $selected = [];
        } else {
            foreach ($selected as $key => $value) {
                $selected[$key] = ['position' => $value];
            }
        }
        return $selected;
    }

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

//    /**
//     * Retrieve selected Images
//
//     * @return array
//     */
//    protected function _getSelectedImages()
//    {
//
//        $images = $this->getStoreImages();
//
//        if (!is_array($images)) {
//            $images = $this->getStore()->getOldImages();
//            return $images;
//        }
//
//        return $images;
//    }

//    /**
//     * Retrieve selected Images
//
//     * @return array
//     */
//    public function getSelectedImages()
//    {
//
//        $selected = $this->getStore()->getOldImages();
//
//        return $selected;
//    }

    /**
     * get grid url
     *
     * @return string
     */
    public function getGridUrl()
    {
        return $this->getUrl(
            '*/*/imagesGrid',
            [
                '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 __('Images');
    }

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

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

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

    /**
     * prepare the collection
     * @return $this
     */
    protected function _prepareCollection()
    {
        /** @var Collection $collection */
        $collection = $this->imageCollectionFactory->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_image')],
            'related.image_id=main_table.image_id AND ' . $constraint,
            ['store_id']
        );

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

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

    /**
     * @return $this|Image
     * @throws Exception
     */
    protected function _prepareColumns()
    {
        $this->addColumn(
            'in_images',
            [
                'header_css_class' => 'a-center',
                'type'             => 'checkbox',
                'name'             => 'in_image',
                'values'           => $this->_getSelectedImages(),
                'align'            => 'center',
                'index'            => 'image_id'
            ]
        );
        $this->addColumn(
            'image_id',
            [
                'header'           => __('ID'),
                'sortable'         => true,
                'index'            => 'image_id',
                'type'             => 'number',
                'header_css_class' => 'col-id',
                'column_css_class' => 'col-id'
            ]
        );

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

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

        $this->addColumn(
            'position',
            [
                'header'         => __('Position'),
                'name'           => 'position',
                'width'          => 60,
                'type'           => 'number',
                'validate_class' => 'validate-number',
                'index'          => 'position',
                'editable'       => true,
            ]
        );

        return $this;
    }

    /**
     * Retrieve selected Images
     * @return array
     */
    protected function _getSelectedImages()
    {
        $tags = $this->getStoreImages();
        if (!is_array($tags)) {
            $tags = $this->getStore()->getImagesPosition();

            return array_keys($tags);
        }


        return $tags;
    }

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

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

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

        return $this;
    }
}
