<?php
/**
 * @author Aitoc Team
 * @copyright Copyright (c) 2020 Aitoc (https://www.aitoc.com)
 * @package Aitoc_PreOrders
 */

/**
 * Copyright © 2018 Aitoc. All rights reserved.
 * Developed by Alex Yakimovich
 */

namespace Aitoc\PreOrders\Model;

use Magento\Framework\Api\SearchCriteriaInterface;
use Magento\Framework\Api\Search\FilterGroup;
use Magento\Framework\App\ProductMetadataInterface;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
use Magento\Framework\Api\SearchResultsInterfaceFactory;
use Magento\Framework\ObjectManagerInterface;

/**
 * Class-resolver for actual and legacy repository functionality
 */
class RepositoryResolver
{
    /**
     * @var ProductMetadataInterface
     */
    private $productMetadata;

    /**
     * @var ObjectManagerInterface
     */
    private $objectManager;

    /**
     * @param ProductMetadataInterface $productMetadata
     * @param ObjectManagerInterface $objectManager
     */
    public function __construct(
        ProductMetadataInterface $productMetadata,
        ObjectManagerInterface $objectManager
    ) {
        $this->productMetadata = $productMetadata;
        $this->objectManager = $objectManager;
    }

    /**
     * @param SearchCriteriaInterface $criteria
     * @param $collection
     * @param $searchResultsFactory
     * @return mixed
     * @throws InputException
     */
    public function getList(SearchCriteriaInterface $criteria, AbstractCollection $collection, $searchResultsFactory)
    {
        $magentoVersion = $this->productMetadata->getVersion();
        $searchResults = $searchResultsFactory->create();
        $searchResults->setSearchCriteria($criteria);
        if (version_compare($magentoVersion, '2.2.0', '<')) {

            // Add filters from root filter group to the collection
            foreach ($criteria->getFilterGroups() as $group) {
                $this->addFilterGroupToCollection($group, $collection);
            }
            $searchResults->setTotalCount($collection->getSize());
            $sortOrders = $criteria->getSortOrders();
            if ($sortOrders) {
                foreach ($sortOrders as $sortOrder) {
                    $field = $sortOrder->getField();
                    $collection->addOrder(
                        $field,
                        ($sortOrder->getDirection() == SortOrder::SORT_ASC) ? 'ASC' : 'DESC'
                    );
                }
            }
            $collection->setCurPage($criteria->getCurrentPage());
            $collection->setPageSize($criteria->getPageSize());

            $items = [];
            foreach ($collection->getItems() as $item) {
                $items[] = $item;
            }
            $searchResults->setItems($items);

        } else {
            $collectionProcessor = $this->objectManager->get("Magento\Framework\Api\SearchCriteria\CollectionProcessor");
            $collectionProcessor->process($criteria, $collection);
            $searchResults
                ->setItems($collection->getItems())
                ->setTotalCount($collection->getSize());
        }

        return $searchResults;
    }

    /**
     * Helper function that adds a FilterGroup to the collection.
     *
     * @param FilterGroup $filterGroup
     * @param AbstractCollection $collection
     * @return void
     * @throws InputException
     */
    protected function addFilterGroupToCollection(FilterGroup $filterGroup, AbstractCollection $collection)
    {
        foreach ($filterGroup->getFilters() as $filter) {
            $condition = $filter->getConditionType() ? $filter->getConditionType() : 'eq';
            $collection->addFieldToFilter($filter->getField(), [$condition => $filter->getValue()]);
        }
    }
}
