<?php

namespace FiloBlu\Esb\Model\Loader;

use FiloBlu\Esb\Api\Data\ObjectTypeDescriptorInterface;
use FiloBlu\Esb\Api\Data\ObjectTypeInterface;
use FiloBlu\Esb\Api\ObjectTypeLoaderInterface;
use FiloBlu\Esb\Framework\ObjectType\Endpoint\AbstractEndpoint;
use Magento\Newsletter\Model\SubscriberFactory;
use RuntimeException;

/**
 * Class SubscriberLoader
 * @package FiloBlu\Esb\Model\Loader
 */
class SubscriberLoader extends AbstractEndpoint implements ObjectTypeLoaderInterface
{
    /**
     * @var SubscriberFactory
     */
    protected $subscriberFactory;

    /**
     * SubscriberLoader constructor.
     * @param SubscriberFactory $subscriberFactory
     * @param ObjectTypeDescriptorInterface $objectTypeDescriptor
     */
    public function __construct(SubscriberFactory $subscriberFactory, ObjectTypeDescriptorInterface $objectTypeDescriptor)
    {
        parent::__construct($objectTypeDescriptor);
        $this->subscriberFactory = $subscriberFactory;
    }

    /**
     * @inheritDoc
     */
    public function get(ObjectTypeInterface $objectType)
    {
        if (!$this->isSuitableFor($objectType)) {
            throw new RuntimeException("Incompatible loader for type {$objectType->getTypeCode()}");
        }

        return $this->subscriberFactory->create()->load($objectType->getId());
    }

    /**
     * @inheritDoc
     */
    public function getName(): string
    {
        return 'Esb subscriber loader';
    }

    /**
     * @inheritDoc
     */
    public function getUniqueName(): string
    {
        return 'FiloBlu_Esb::subscriber_loader';
    }
}
