<?php

namespace FiloBlu\Esb\Ui\Component\Producer\Form;

use FiloBlu\Esb\Api\Data\ProducerConfigurationInterface;
use FiloBlu\Esb\Api\ProducerConfigurationRepositoryInterface;
use FiloBlu\Esb\Ui\Component\AbstractDataProvider;
use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\Search\SearchCriteriaBuilder;
use Magento\Framework\App\RequestInterface;

/**
 * Class DataProvider
 * @package FiloBlu\Esb\Ui\Component\Consumer\Form
 */
class DataProvider extends AbstractDataProvider
{

    /**
     * @var ProducerConfigurationRepositoryInterface
     */
    protected $itemRepository;
    /**
     * @var RequestInterface
     */
    private $request;

    /**
     * @param string $name
     * @param string $primaryFieldName
     * @param string $requestFieldName
     * @param ProducerConfigurationRepositoryInterface $itemRepository
     * @param SearchCriteriaBuilder $searchCriteriaBuilder
     * @param FilterBuilder $filterBuilder
     * @param RequestInterface $request
     * @param array $meta
     * @param array $data
     */
    public function __construct(
        $name,
        $primaryFieldName,
        $requestFieldName,
        ProducerConfigurationRepositoryInterface $itemRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        FilterBuilder $filterBuilder,
        RequestInterface $request,
        array $meta = [],
        array $data = []
    ) {
        parent::__construct($name, $primaryFieldName, $requestFieldName, $searchCriteriaBuilder, $filterBuilder, $request, $meta, $data);
        $this->itemRepository = $itemRepository;
        $this->request = $request;
    }

    /**
     * @inheritDoc
     */
    public function getData()
    {
        $type = $this->request->getParam('type', null);

        if ($type !== null) {
            return [
                null => [
                    'general' => [
                        'producer' => [
                            ProducerConfigurationInterface::PRODUCER => $type,
                            ProducerConfigurationInterface::PARAMETERS => '{"conditions": [] , "payload":{} }'
                        ]
                    ]
                ]
            ];
        }

        $result = $this->itemRepository->getList($this->getSearchCriteria(), true);

        $data = [];

        // @see \Magento\Ui\Component\Form
        foreach ($result->getItems() as $item) {
            $data[$item[$this->primaryFieldName]]['general']['producer'] = $item;
        }

        return $data;
    }

    /**
     * @inheritDoc
     */
    public function getSearchResult()
    {
        $searchCriteria = $this->getSearchCriteria();
        return $this->itemRepository->getList($searchCriteria);
    }
}
