<?php

namespace FiloBlu\Esb\Model;

use FiloBlu\Esb\Api\RetryStrategyInterface;
use FiloBlu\Esb\Api\RetryStrategyResolverInterface;
use Magento\Framework\Exception\NoSuchEntityException;

/**
 * Class RetryStrategyResolver
 * @package FiloBlu\Esb\Model
 */
class RetryStrategyResolver implements RetryStrategyResolverInterface
{

    /**
     * @var array
     */
    private $strategies;
    /**
     * @var RetryStrategyInterface
     */
    private $defaultStrategy;

    /**
     * RetryStrategyResolver constructor.
     * @param RetryStrategyInterface $defaultStrategy
     * @param array $strategies
     */
    public function __construct(
        RetryStrategyInterface $defaultStrategy,
                                array $strategies
    ) {
        $this->strategies = $strategies;
        $this->defaultStrategy = $defaultStrategy;
    }

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

    /**
     * @inheritDoc
     */
    public function get(string $name): RetryStrategyInterface
    {
        $nameOrClass = trim($name, '\\');

        foreach ($this->strategies as $key => $instance) {
            if ($key === $name) {
                return $instance;
            }

            if (get_class($instance) === $nameOrClass) {
                return $instance;
            }
        }

        throw new NoSuchEntityException(__('Could not find a retry strategy with name or class "%1"', $name));
    }

    /**
     * @inheritDoc
     */
    public function getDefault(): RetryStrategyInterface
    {
        return $this->defaultStrategy;
    }
}
