<?php

namespace FiloBlu\Refilo\Remote\Connector;

use Magento\Framework\ObjectManagerInterface;
use RuntimeException;

/**
 * Class ConnectorPool
 * @package FiloBlu\Refilo\Remote\Connector
 */
class ConnectorPool
{
    /**
     * @var array
     */
    private $connectors;
    /**
     * @var ObjectManagerInterface
     */
    private $objectManager;

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

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

    /**
     * @return array
     */
    public function getAll()
    {
        return $this->connectors;
    }

    /**
     * @param ConnectorInterface $connector
     * @return int|string
     */
    public function getTypeFor(ConnectorInterface $connector)
    {
        $connectorClass = trim(get_class($connector), '\\');
        foreach ($this->connectors as $type => $class) {
            if (trim($class, '\\') === $connectorClass) {
                return $type;
            }
        }

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