<?php

namespace App\Mailer;

use Illuminate\Mail\TransportManager;
use Illuminate\Support\Facades\Config;
use Swift_DependencyContainer;
use Swift_Mailer;

class DynamicMailerManager
{
    public function __construct($app)
    {
        $this->app = $app;
    }

    protected function registerSwiftTransport()
    {
        $this->app->singleton('swift.transport', function () {
            return new TransportManager($this->app);
        });
    }

    protected function registerSwiftMailer()
    {
        $this->registerSwiftTransport();

        // Once we have the transporter registered, we will register the actual Swift
        // mailer instance, passing in the transport instances, which allows us to
        // override this transporter instances during app start-up if necessary.
        $this->app->singleton('swift.mailer', function () {
            if ($domain = $this->app->make('config')->get('mail.domain')) {
                Swift_DependencyContainer::getInstance()
                                ->register('mime.idgenerator.idright')
                                ->asValue($domain);
            }

            return new Swift_Mailer($this->app['swift.transport']->driver());
        });
    }

    public function getMailer($mailConfig)
    {
        Config::set($mailConfig);

        $this->registerSwiftMailer();

        return $this->app['swift.mailer'];
    }
}