<?php

namespace FiloBlu\Esb\Model;

use FiloBlu\Esb\Api\Data\ProducerInterface;
use FiloBlu\Esb\Api\ProducerResolverInterface;
use Magento\Framework\Exception\NoSuchEntityException;
use Throwable;

/**
 * Class ConsumerResolver
 * @package FiloBlu\Esb\Model
 */
class ProducerResolver implements ProducerResolverInterface
{
    /**
     * @var array
     */
    protected $producers = [];
    /**
     * @var array
     */
    protected $producersByEvent = [];

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

    /**
     *
     * @param string $identifier
     * @return ProducerInterface
     * @throws NoSuchEntityException
     */
    public function get($identifier): ProducerInterface
    {
        /** @var ProducerInterface $producer */
        foreach ($this->producers as $producer) {
            if ($producer->getUniqueName() === $identifier) {
                return $producer;
            }
        }

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

    /**
     * @param string $identifier
     * @return boolean
     */
    public function has($identifier): bool
    {
        return array_key_exists($identifier, $this->getProducersByEvent());
    }

    /**
     *
     * @return array
     */
    public function getProducersByEvent(): array
    {
        if (!empty($this->producersByEvent)) {
            return $this->producersByEvent;
        }

        /** @var ProducerInterface $producer */
        foreach ($this->producers as $producer) {
            try {
                $typeCode = $producer->getObjectTypeDescriptor()->getTypeCode();
                $this->producersByEvent[$typeCode][] = $producer;
            } catch (NoSuchEntityException $exception) {
                continue;
            } catch (Throwable $throwable) {
                continue;
            }
        }

        return $this->producersByEvent;
    }

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