<?php

namespace FiloBlu\Refilo\Ui\Component\Redirects\Form;

use FiloBlu\Refilo\Model\Redirects\Interfaces\RedirectInterface;
use FiloBlu\Refilo\Model\Redirects\Interfaces\RedirectsRepositoryInterface;
use FiloBlu\Refilo\Ui\Component\Redirects\AbstractDataProvider;
use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\Search\SearchCriteriaBuilder;
use Magento\Framework\App\RequestInterface;

/**
 * Class DataProvider
 * @package FiloBlu\Refilo\Ui\Component\Redirects\Form
 */
class DataProvider extends AbstractDataProvider
{

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

    /**
     * @param string $name
     * @param string $primaryFieldName
     * @param string $requestFieldName
     * @param RedirectsRepositoryInterface $itemRepository
     * @param SearchCriteriaBuilder $searchCriteriaBuilder
     * @param FilterBuilder $filterBuilder
     * @param RequestInterface $request
     * @param array $meta
     * @param array $data
     */
    public function __construct(
        $name,
        $primaryFieldName,
        $requestFieldName,
        RedirectsRepositoryInterface $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()
    {
        $result = $this->itemRepository->getList($this->getSearchCriteria(), true);

        $data = [];

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

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