<?php

namespace FiloBlu\Refilo\Remote\IndexerConfiguration;

use Magento\Framework\Exception\NoSuchEntityException;
use function get_class;
use function is_object;

/**
 * Class IndexerResolver
 * @package FiloBlu\Refilo\Remote\IndexerConfiguration
 */
class IndexerResolver
{
    /**
     * @var IndexerPool
     */
    protected $indexerPool;

    /**
     * IndexerResolver constructor.
     * @param IndexerPool $indexerPool
     */
    public function __construct(IndexerPool $indexerPool)
    {
        $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->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->indexerPool->getAll() as $key => $item) {
            $indexers[] = $key;
        }
        return $indexers;
    }


    /**
     * Returns the IndexerPool instance.
     *
     * @return IndexerPool
     */
    public function getIndexerPool(): IndexerPool
    {
        return $this->indexerPool;
    }

}
