<?php

namespace FiloBlu\Esb\Model;

use FiloBlu\Esb\Api\ConsumerResolverInterface;
use FiloBlu\Esb\Api\Data\ConsumerInterface;
use Magento\Framework\Exception\NoSuchEntityException;

/**
 * Class ConsumerResolver
 * @package FiloBlu\Esb\Model
 */
class ConsumerResolver implements ConsumerResolverInterface
{
    /**
     * @var array
     */
    protected $consumers = [];

    /**
     * @var array
     */
    protected $consumerByEvent = [];

    /**
     * ConsumerResolver constructor.
     * @param array $consumers
     */
    public function __construct(array $consumers)
    {
        $this->consumers = $consumers;
    }

    /**
     * @param string $identifier
     * @return ConsumerInterface
     * @throws NoSuchEntityException
     */
    public function get($identifier): ConsumerInterface
    {
        foreach ($this->consumers as $consumer) {
            if ($consumer->getUniqueName() === $identifier) {
                return clone $consumer;
            }

            if ($consumer instanceof $identifier) {
                return clone $consumer;
            }
        }

        throw new NoSuchEntityException(__('No producer defined with unique name "%1"', $identifier));
    }

    /**
     * @param string $identifier
     * @return boolean
     */
    public function has($identifier): bool
    {
        foreach ($this->consumers as $consumer) {
            if ($consumer->getUniqueName() === $identifier) {
                return true;
            }
        }

        return false;
    }

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