<?php

namespace HS\Mail;

use Swift_Mailer;
use Swift_SmtpTransport;
use Swift_SendmailTransport;

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


class HelpspotMailer
{
    /**
     * @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);
            }
            return new Swift_Mailer($transport);
        });

        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;
        });
    }
}
