import * as NodeMailer from "nodemailer";
import Utils from "./utils";
import * as Index from "./index.d"
import { MultipleInstanceInterface } from "./multipleInstanceInterface";
import Settings from "./settings";

export default class Mailer implements MultipleInstanceInterface {

    private static STATUS = {
        READY: "ready", // default, could also be '' or undefined
        CONNECTED: "connected",
        DISCONNECTED: "disconnected",
        ERROR: "error"
    };
    private config: Index.MailerOptions;
    private mailTransport: NodeMailer.Transporter | null = null;
    private status = Mailer.STATUS.READY;
    constructor(tag: string = "tag") {
        this.config = Settings.Instance.getMailer(tag);
    }
    private connect(){
        this.mailTransport = NodeMailer.createTransport(this.config.mailTransportConfig);        
        this.status = Mailer.STATUS.CONNECTED;
    }

    public sendMail(mailOptions: NodeMailer.SendMailOptions, callback: (err: Error | null, info: NodeMailer.SentMessageInfo) => void ){
        if(this.mailTransport == null){
            this.connect();
        };

        let self = this;
        let interceptedCallback = function (err: Error | null, info: NodeMailer.SentMessageInfo){

            //mark that we have an error when we attempted to send an email and failed!
            if(err != null){
                self.status = Mailer.STATUS.ERROR;
            }
            callback(err, info);
        }
        
        if(this.mailTransport != null){
            let options = Utils.deepExtend({}, this.config.mailConfig, mailOptions);
            this.mailTransport.sendMail(options, interceptedCallback);            
        }

        this.destroy();
    }

    public destroy(){
        // clearInterval(this.interval);
        if(this.mailTransport != null){
            this.mailTransport.close();
            this.mailTransport = null;
        }
        this.status =  Mailer.STATUS.DISCONNECTED;
    } 
    
    public getStatus(){
        return this.status.toString();
    }

    public isFunctional(){
        return Mailer.STATUS.ERROR != this.status;
    }
}
