<?php

namespace FiloBlu\Refilo\Remote\IndexerConfiguration;

use FiloBlu\Refilo\Remote\IndexerInterface;
use Magento\Framework\ObjectManagerInterface;
use RuntimeException;
use function get_class;

/**
 * Class IndexerPool
 * @package FiloBlu\Refilo\Remote\IndexerConfiguration
 */
class IndexerPool
{

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

    /**
     * IndexerPool constructor.
     * @param ObjectManagerInterface $objectManager
     * @param array $indexers
     */
    public function __construct(ObjectManagerInterface $objectManager, array $indexers)
    {
        $this->indexers = $indexers;
        $this->objectManager = $objectManager;
    }

    /**
     * @param string $name
     * @param array $data
     * @return IndexerInterface
     */
    public function get(string $name, array $data = []): IndexerInterface
    {
        return $this->objectManager->create($this->indexers[$name], $data);
    }

    /**
     * @return string[]
     */
    public function getAll(): array
    {
        return $this->indexers;
    }

    /**
     * @param IndexerInterface $indexer
     * @return int|string
     */
    public function getTypeFor(IndexerInterface $indexer)
    {
        $indexerClass = trim(get_class($indexer), '\\');
        foreach ($this->indexers as $type => $class) {
            if (trim($class, '\\') === $indexerClass) {
                return $type;
            }
        }

        throw new RuntimeException("Could not resolve type for {$indexerClass}");
    }

    /**
     * @param string $name
     * @return bool
     */
    public function has(string $name) :bool
    {
        return isset($this->indexers[$name]);
    }
}
