"use strict";
const nodemailer = require("nodemailer");

// async..await is not allowed in global scope, must use a wrapper
async function dosendmail(develop, from, to, subject, bodyTxt, bodyHtml, bcc, cc) {
    let transportOptions = 
        develop ? {
		host: 'mailhog',
		port: 1025
	} : {
		host: "sslout.df.eu",
        	port: 465,
        	secure: true, // true for 465, false for other ports
        	auth: {
            		user: 'sonderfuehrung@sternwarte-welzheim.de', // generated ethereal user
            		pass: 'M45-Plejaden', // generated ethereal password
        	},
	}

    const buildAddrString = (addr) => {
	let list = ""
	for (let a of addr) {
	    list += a + ','
        }
	list = list.slice(0,-1)
	console.log(list)
        return list
    }

    console.log(transportOptions)

    // cretae new transporter
    let transporter = nodemailer.createTransport(transportOptions)
    
    // send mail with defined transport object
    let info = await transporter.sendMail({
        from: from, 		// sender address
        to: buildAddrString(to), 		// list of receivers
        subject: subject, 	// Subject line
        text: bodyTxt,		// plain text body
        html: bodyHtml, 	// html body
    });

    console.log("Message sent: %s", info.messageId);
    // Message sent: <b658f8ca-6296-ccf4-8306-87d57a0b4321@example.com>

}

dosendmail(false, 'anmeldung@sternwarte-welzheim.de', ['rxf@gmx.de', 'rexfue@gmail.com', 'rxf@fuerst-stuttgart.de'], 'der ultimative Test', "Text in polain text", "<h1>Text</h1> in dummene <strong>HTML</strong>").catch(console.error);

/*
function sendmail($subject, $from, $body, $cc=[], $bcc=[], $to=[]) {
    global $develop;

    $ret = [];
    $ret['error'] = false;


    $mail = new PHPMailer();
    $mail->CharSet = 'utf-8';
    $mail->isSMTP();
    if ($develop == 'true') {
        $mail->Host = 'mailhog';
        $mail->Port = 1025;
    } else {
        $mail->SMTPAuth = true;
        $mail->Host = "sslout.df.eu";
        $mail->Port = "465";
        $mail->SMTPSecure = "ssl";
        $mail->Username = "sonderfuehrung@sternwarte-welzheim.de";
        $mail->Password = "M45-Plejaden";
    }
    $mail->setFrom($from);
    if (count($to) != 0) {
        foreach ($to as $t) {
            $mail->addAddress($t);
        }
    }
    $mail->Subject = $subject;
    $mail->Body = $body;
    if (count($cc) != 0) {
        foreach ($cc as $c) {
            $mail->addCC($c);
        }
    }
    if(count($bcc) != 0) {
        foreach ($bcc as $bc) {
            $mail->addBCC($bc);
        }
    }
    $mail->addReplyTo($from);

    if (!$mail->send()) {
        $ret['error'] = true;
        $ret['errortext'] = $mail->ErrorInfo;
    }
    return $ret;
}
*/
