<?php
namespace FiloBlu\Refilo\Ui\Component\ContentManager;

use Blackbird\ContentManager\Model\ResourceModel\Content\CollectionFactory as ContentCollectionFactory;
use FiloBlu\Core\Framework\Ui\AbstractDataProvider;
use FiloBlu\Refilo\Helper\ContentManager\Data as ContentManagerHelper;
use Magento\Framework\Api\FilterBuilder;
use Magento\Framework\Api\Search\SearchCriteriaBuilder;
use Magento\Framework\App\RequestInterface;

/**
 *
 */
class DataProvider extends AbstractDataProvider
{
    /**
     * @var ContentCollectionFactory
     */
    protected $contentCollectionFactory;

    /**
     * @var ContentManagerHelper
     */
    protected $contentHelper;

    /**
     * @param \Blackbird\ContentManager\Model\ResourceModel\Content\CollectionFactory $contentCollectionFactory
     * @param \FiloBlu\Refilo\Helper\ContentManager\Data $contentHelper
     * @param string $name
     * @param string $primaryFieldName
     * @param string $requestFieldName
     * @param SearchCriteriaBuilder $searchCriteriaBuilder
     * @param FilterBuilder $filterBuilder
     * @param RequestInterface $request
     * @param array $meta
     * @param array $data
     */
    public function __construct(
        ContentCollectionFactory $contentCollectionFactory,
        ContentManagerHelper $contentHelper,
        $name,
        $primaryFieldName,
        $requestFieldName,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        FilterBuilder $filterBuilder,
        RequestInterface $request,
        array $meta = [],
        array $data = []
    ) {
        parent::__construct(
            $name,
            $primaryFieldName,
            $requestFieldName,
            $searchCriteriaBuilder,
            $filterBuilder,
            $request,
            $meta,
            $data
        );
        $this->contentCollectionFactory = $contentCollectionFactory;
        $this->contentHelper = $contentHelper;
    }

    /**
     * @inheritDoc
     */
    public function getData()
    {
        $items = $this->getSearchResult()->toArray();

        foreach ($items as $key => $item) {
            $items[$key]['content_type'] = $this->contentHelper->getIdentifierFromId($item['ct_id']);
        }

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

    /**
     * @inheritDoc
     */
    public function getSearchResult()
    {
        return $this->contentCollectionFactory->create()->addAttributeToSelect('*');
    }

    #[\ReturnTypeWillChange]
    public function count()
    {
        return count($this->getSearchResult()->getItems());
    }
}
