<?php

namespace FiloBlu\Refilo\Remote\IndexerConfiguration;

use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Indexer\Model\Indexer\Collection;
use Magento\Indexer\Model\Indexer\CollectionFactory;

/**
 * Class IndexerResolver
 * @package FiloBlu\Refilo\Remote\IndexerConfiguration
 */
class IndexerResolver
{
    /**
     * @var Collection
     */
    protected $indexerCollection;
    /**
     * @var IndexerPool
     */
    protected $indexerPool;
    /**
     * @var CollectionFactory
     */
    private $indexerCollectionFactory;

    /**
     * IndexerResolver constructor.
     * @param CollectionFactory $indexerCollectionFactory
     * @param IndexerPool $indexerPool
     */
    public function __construct(
        CollectionFactory $indexerCollectionFactory,
        IndexerPool $indexerPool
    ) {
        $this->indexerCollectionFactory = $indexerCollectionFactory;
        $this->indexerPool = $indexerPool;
    }

    /**
     * @param $indexer
     * @return string
     * @throws NoSuchEntityException
     */
    public function resolve($indexer): string
    {
        $indexerClass = $indexer;
        if (is_object($indexer)) {
            $indexerClass = get_class($indexer);
        }
        foreach ($this->getIndexerCollection()->getItems() as $item) {
            if ($this->equal($item->getActionClass(), $indexerClass)) {
                return $item->getId();
            }
        }
        foreach ($this->indexerPool->getAll() as $key => $item) {
            if ($this->equal($item, $indexerClass)) {
                return $key;
            }
        }

        throw new NoSuchEntityException(__("Unable to find {$indexerClass}"));
    }

    /**
     * @param $class1
     * @param $class2
     * @return bool
     */
    public function equal($class1, $class2)
    {
        return trim($class1, '\\') === trim($class2, '\\');
    }

    /**
     * @return array
     */
    public function getIndexerIds(): array
    {
        $indexers = [];
        foreach ($this->getIndexerCollection()->getAllIds() as $id) {
            if (strpos($id, 'beehive_') === 0) {
                $indexers[] = $id;
            }
        }
        foreach ($this->indexerPool->getAll() as $key => $item) {
            $indexers[] = $key;
        }
        return $indexers;
    }

    /**
     * @return Collection
     */
    public function getIndexerCollection()
    {
        if ($this->indexerCollection === null) {
            $this->indexerCollection = $this->indexerCollectionFactory->create();
        }

        return $this->indexerCollection;
    }
}
