<?php

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

use FiloBlu\Esb\Api\Data\QueueConfigurationInterface;
use FiloBlu\Esb\Api\QueueConfigurationRepositoryInterface;
use FiloBlu\Esb\Api\QueueItemRepositoryInterface;
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\Queue\Form
 */
class DataProvider extends AbstractDataProvider
{

    /**
     * @var QueueItemRepositoryInterface
     */
    protected $itemRepository;

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

    /**
     * @inheritDoc
     */
    public function getData()
    {
        $result = $this->itemRepository->getList($this->getSearchCriteria(), true);

        $data = [];

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

    }

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