<?php
/**
 * Copyright © 2018 Wyomind. All rights reserved.
 * See LICENSE.txt for license details.
 */

namespace Wyomind\ElasticsearchCore\Ui\DataProvider\Listing;

/**
 * Class Browse
 * @package Wyomind\ElasticsearchCore\Ui\DataProvider\Listing
 */
class Browse extends \Magento\Ui\DataProvider\AbstractDataProvider
{
    /**
     * @var int
     */
    protected $_size = 20;

    /**
     * @var int
     */
    protected $_offset = 1;

    /**
     * @var array
     */
    protected $_likeFilters = [];

    /**
     * @var array
     */
    protected $_rangeFilters = [];

    /**
     * @var string
     */
    protected $_sortField = 'id';

    /**
     * @var string
     */
    protected $_sortDir = 'asc';

    /**
     * @var \Wyomind\ElasticsearchCore\Helper\Indexer|null
     */
    private $_indexerHelper = null;

    /**
     * @var \Wyomind\ElasticsearchCore\Helper\Session|null
     */
    private $_sessionHelper = null;

    /**
     * Browse constructor.
     * @param string $name
     * @param string $primaryFieldName
     * @param string $requestFieldName
     * @param \Wyomind\ElasticsearchCore\Helper\Indexer $indexerHelper
     * @param \Wyomind\ElasticsearchCore\Helper\Session $sessionHelper
     * @param array $meta
     * @param array $data
     */
    public function __construct(
        $name,
        $primaryFieldName,
        $requestFieldName,
        \Wyomind\ElasticsearchCore\Helper\Indexer $indexerHelper,
        \Wyomind\ElasticsearchCore\Helper\Session $sessionHelper,
        array $meta = [],
        array $data = []
    )
    {
        $this->_indexerHelper = $indexerHelper;
        $this->_sessionHelper = $sessionHelper;
        parent::__construct($name, $primaryFieldName, $requestFieldName, $meta, $data);
    }

    public function setLimit($offset, $size)
    {
        $this->_size = $size;
        $this->_offset = $offset;
    }

    public function getData()
    {
        list($type, $indice, $store, $storeId) = $this->_sessionHelper->getBrowseData();

        if ($indice == null) {
            return [
                'totalRecords' => 0,
                'items' => [],
            ];
        }

        $query = [];

        foreach ($this->_likeFilters as $field => $value) {
            $query['bool']['must'][] = [
                'match' => [
                    $field => $value
                ]
            ];
        }

        foreach ($this->_rangeFilters as $field => $fromTo) {
            $query['bool']['filter'][] = [
                'range' => [
                    $field => $fromTo
                ]
            ];
        }

        $params = [
            'body' => [
                'from' => ($this->_offset - 1) * $this->_size,
                'size' => $this->_size,
                'query' => $query
            ],
        ];

        if (!isset($query['bool']['filter'])) {
            $params['body']['sort'] = [
                $this->_sortField => $this->_sortDir
            ];
        }

        try {
            $config = new \Wyomind\ElasticsearchCore\Helper\Autocomplete\Config($store);

            if (!$config->getData()) {
                throw new \Exception('Could not find config');
            }

            $client = new \Wyomind\ElasticsearchCore\Model\Client($config);

            $client->init($store);

            $params['from_admin'] = true;

            $info = $client->info();
            $serverVersion = $info['version']['number'];

            if (empty($params['body']['query'])) {
                // ES 5.x
                $query = new \stdClass();
                $params['body']['query'] = ['match_all' => $query];
                // ES 2.x
                if (version_compare($serverVersion, '5.0.0') < 0) {
                    unset($params['body']['query']);
                }
            }
            $response = $client->query($indice, $type, $params);

            $docs = [];
            foreach ($response['hits']['hits'] as $doc) {
                $docs[] = $doc['_source'];
            }

            $count = $response['hits']['total'];
            $result = [
                'count' => $count,
                'docs' => $docs
            ];
        } catch (\Exception $e) {
            return [
                'totalRecords' => 0,
                'items' => []
            ];
        }

        $this->_sessionHelper->setBrowseData([$type, $indice, $store, $storeId]);

        $return = [
            'totalRecords' => $result['count'],
            'items' => array_values($result['docs'])
        ];

        return $return;
    }

    /**
     * @param \Magento\Framework\Api\Filter $filter
     */
    public function addFilter(\Magento\Framework\Api\Filter $filter)
    {
        if ($filter->getConditionType() == 'like') {
            $this->_likeFilters[$filter->getField()] = substr($filter->getValue(), 1, -1);
        } elseif ($filter->getConditionType() == 'eq') {
            $this->_likeFilters[$filter->getField()] = $filter->getValue();
        } elseif ($filter->getConditionType() == 'finset') {
            $this->_likeFilters[$filter->getField() . '_ids'] = $filter->getValue();
        } elseif ($filter->getConditionType() == 'gteq') {
            $this->_rangeFilters[$filter->getField()]['from'] = $filter->getValue();
        } elseif ($filter->getConditionType() == 'lteq') {
            $this->_rangeFilters[$filter->getField()]['to'] = $filter->getValue();
        }
    }

    public function addOrder($field, $direction)
    {
        $this->_sortField = $field;
        $this->_sortDir = strtolower($direction);
    }

############################################################################

    public function addField($field, $alias = null)
    {

    }

    public function count()
    {

    }

    public function getSearchResult()
    {

    }

    public function removeField($field, $isAlias = false)
    {

    }

    public function removeAllFields()
    {

    }
}