<?php

namespace HS\Mail;

use Swift_Mailer;
use Swift_Plugins_LoggerPlugin;
use Swift_Plugins_Loggers_ArrayLogger;
use Swift_SmtpTransport;
use Swift_SendmailTransport;

use HS\Mail\Mailer\SMTP;
use HS\Mail\Mailer\SmtpSettings;


class HelpspotMailer
{
    /**
     * @var Swift_Plugins_Loggers_ArrayLogger
     * usage: `HelpspotMailer::$logger->dump()`
     */
    public static $logger;

    /**
     * @param $mailboxId
     * @return Mailer
     * @throws \Exception
     */
    public static function via($mailboxId)
    {
        // No mailbox specific, and default is sendmail
        if ($mailboxId == 0 && config()->get('mail.default') != 'smtp') {
            $swift = new Swift_Mailer(new Swift_SendmailTransport);
            return self::generateMailer($swift, 'sendmail');
        }

        // Use SMTP
        if ($mailboxId instanceof SMTP) {
            $smtp = $mailboxId;
        } else {
            $smtp = (new SmtpSettings($mailboxId))
                ->settings();
        }

        // Mailbox has no custom SMTP and
        // system default is sendmail
        if ($smtp === false) {
            $swift = new Swift_Mailer(new Swift_SendmailTransport);
            return self::generateMailer($swift, 'sendmail');
        }

        $swift = with(new Swift_SmtpTransport($smtp->host, $smtp->port, $smtp->encryption), function($transport) use($smtp) {
            if( $smtp->auth ) {
                $transport->setUsername($smtp->username);
                $transport->setPassword($smtp->password);
            }
            if ($smtp->helo) {
                $transport->setLocalDomain($smtp->helo);
            }
            return new Swift_Mailer($transport);
        });

        $logger = new Swift_Plugins_Loggers_ArrayLogger();
        self::$logger = $logger;
        $swift->registerPlugin(new Swift_Plugins_LoggerPlugin($logger));

        return static::generateMailer($swift);
    }

    public static function generateMailer($swift, $name='smtp')
    {
        return with(new Mailer($name, app('view'), $swift, app('events')), function(Mailer $mailer) {
            $mailer->setQueue(app('queue'));
            return $mailer;
        });
    }
}
