<?php

namespace KupShop\KupShopBundle\Util\Mail;

use KupShop\KupShopBundle\Email\EmailInterface;
use KupShop\KupShopBundle\EmailRegister\EmailRegisterInterface;
use KupShop\KupShopBundle\Exception\UnknownEmailTypeException;
use Symfony\Component\DependencyInjection\ServiceLocator;

class EmailLocator
{
    private $locator;
    private $emails;

    private $emailRegisterLocator;

    public function __construct(ServiceLocator $locator, array $emails)
    {
        $this->locator = $locator;
        $this->emails = $emails;
    }

    public function setEmailRegisterLocator(ServiceLocator $emailRegisterLocator): void
    {
        $this->emailRegisterLocator = $emailRegisterLocator;
    }

    public function getEmailRegisters(): iterable
    {
        foreach ($this->emailRegisterLocator->getProvidedServices() as $service) {
            yield $this->getEmailRegister($service);
        }
    }

    public function getEmails(): array
    {
        return $this->emails;
    }

    public function getEmailRegister(string $class): EmailRegisterInterface
    {
        if (!$this->emailRegisterLocator->has($class)) {
            throw new \InvalidArgumentException(
                sprintf('Unknown email register: %s', $class)
            );
        }

        return $this->emailRegisterLocator->get($class);
    }

    /**
     * @return EmailInterface
     *
     * @throws UnknownEmailTypeException
     */
    public function getEmailService(string $type)
    {
        if (isset($this->emails[$type])) {
            $class = $this->emails[$type]['class'];

            if ($this->locator->has($class)) {
                /** @var EmailInterface $service */
                $service = $this->locator->get($class);

                return $service;
            }
        }

        throw new UnknownEmailTypeException($type);
    }

    public function getTestType(): ?string
    {
        return null;
    }
}
