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 interval: number;        
    private config: Index.MailerOptions;
    // private tag: string;

    private mailTransport: NodeMailer.Transporter | null = null;

    // protected status: string;
    private waitForStatus = false

    constructor(tag: string = "tag") {
        this.config = Settings.Instance.getMailer(tag);
        
        // let statusInterval =  this.config.statusCheckInterval;
        // if(statusInterval == null || typeof statusInterval != "number" || statusInterval < 1){
        //     statusInterval = 5000;
        // }

        // this.status = "";        
        // this.tag = tag;

        //this.connect();

        // this.statusCheck();
        // this.interval = setInterval(this.statusCheck.bind(this), statusInterval);
    }
    private connect(){
        this.mailTransport = NodeMailer.createTransport(this.config.mailTransportConfig);        
    }

    private statusCheck() {
        // if (this.waitForStatus) return;

        // if(this.mailTransport == null){
        //     this.status = "disconnected";
        //     return;
        // }

        // this.waitForStatus = true;
        // let self = this;
        
        // this.mailTransport.verify(function(err: Error | null, success: boolean): void {
        //     self.waitForStatus = false;

        //     if (err) {
        //         self.status = "error";
        //     } else {
        //         self.status = "connected";
        //     }
        //  });
    }

    public sendMail(mailOptions: NodeMailer.SendMailOptions, callback: (err: Error | null, info: NodeMailer.SentMessageInfo) => void ){
        if(this.mailTransport == null){
            this.connect();
        }
        
        if(this.mailTransport != null){
            let options = Utils.deepExtend({}, this.config.mailConfig, mailOptions);
            this.mailTransport.sendMail(options, callback);            
        }

        this.destroy();
    }

    public destroy(){
        // clearInterval(this.interval);
        if(this.mailTransport != null){
            this.mailTransport.close();
            this.mailTransport = null;
        }
    } 
    
    public getStatus(){
        return (this.mailTransport == null) ? 'connected' : 'discconnected';
    }

    public isFunctional(){
        return this.getStatus() == "connected";
    }
}
