<?php

namespace FiloBlu\Esb\Model;

use FiloBlu\Esb\Api\Data\ObjectTypeDescriptorInterface;
use FiloBlu\Esb\Api\ObjectTypeSaverInterface;
use RuntimeException;

/**
 * Class ObjectTypeSaverResolver
 * @package FiloBlu\Esb\Model
 */
class ObjectTypeSaverResolver implements ObjectTypeSaverResolverInterface
{
    /** @var array */
    protected $savers = [];

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

    /**
     * @inheritDoc
     */
    public function get($uniqueName): ObjectTypeSaverInterface
    {
        /**
         * @var ObjectTypeSaverInterface $saver
         */
        foreach ($this->savers as $saver) {
            if ($saver->getUniqueName() === $uniqueName) {
                return $saver;
            }
        }

        throw new RuntimeException(__('no saver found'));
    }

    /**
     * @inheritDoc
     */
    public function has($name): bool
    {
        /** @var ObjectTypeSaverInterface $loader */
        foreach ($this->savers as $loader) {
            if ($loader->getUniqueName() === $name) {
                return true;
            }
        }

        return false;
    }

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

    /**
     * @inheritDoc
     */
    public function getFor(ObjectTypeDescriptorInterface $objectTypeDescriptor)
    {
        /**
         * @var ObjectTypeSaverInterface $saver
         */
        foreach ($this->savers as $saver) {
            if ($saver->isSuitableFor($objectTypeDescriptor)) {
                return $saver;
            }
        }

        throw new RuntimeException(__('no saver found'));
    }
}
