<?php

namespace Velis\Mail\Transport;

use Psr\SimpleCache\InvalidArgumentException;
use Velis\Bpm\Email\Account;
use Velis\Mail\Mail;
use Velis\Lang;
use DomainException;

/**
 * @author Daniel Zaucha <daniel.zaucha@velis.pl>
 */
class TransportFactory
{
    /**
     * @var Mail
     */
    private $mail;

    /**
     * @var Account
     */
    private $emailAccount;

    public function __construct($mail)
    {
        $this->mail = $mail;
        $this->emailAccount = $mail->getEmailAddress();
    }

    /**
     * Creates aws or smtp instance
     *
     * @throws DomainException if trying to send email through standard mailbox while having SES notifications enabled
     */
    public function create()
    {
        if (AwsSes::isEnabled()) {
            if ($this->emailAccount && !$this->emailAccount->aws_ses) {
                throw new DomainException(
                    Lang::get('EMAIL_STANDARD_SEND_WITH_SES_ENABLED_ERROR') . ': ' . $this->mail->getEmailAddress()
                );
            }
            return $this->getAwsSesInstance();
        } else {
            return $this->getSmptInstance();
        }
    }

    /**
     * @return Smtp
     * @throws InvalidArgumentException
     */
    private function getSmptInstance()
    {
        return Mail::getSmtp($this->emailAccount);
    }

    /**
     * @return AwsSes
     */
    private function getAwsSesInstance()
    {
        return new AwsSes();
    }
}
