package snailmail

import (
	"encoding/base64"
	"fmt"
	"log"
	"mime"
	"net/mail"
	"net/smtp"
	"strings"
	"time"
)

type smtpSender struct{}

func (s *smtpSender) Send(message Email, mailtype int) error {
	recipientString := strings.Join(message.Recipients, ",")
	from := mail.Address{Name: settings.SMTP.DisplayFrom, Address: settings.SMTP.Username}

	header := make(map[string]string)
	header["To"] = recipientString
	header["From"] = from.String()
	header["Subject"] = mime.QEncoding.Encode("UTF-8", message.Subject)
	header["MIME-Version"] = "1.0"
	header["Content-Transfer-Encoding"] = "base64"
	header["Date"] = time.Now().Format(time.RFC1123)

	if mailtype == TYPE_HTML {
		header["Content-Type"] = "text/html; charset=\"utf-8\""
	} else {
		header["Content-Type"] = "text/plain; charset=\"utf-8\""
	}

	email := ""
	for k, v := range header {
		email += fmt.Sprintf("%s: %s\r\n", k, v)
	}
	email += "\r\n" + base64.StdEncoding.EncodeToString(message.Body.Bytes())

	var auth smtp.Auth = nil

	if settings.SMTP.RequireAuth {
		auth = smtp.PlainAuth("", settings.SMTP.Username, settings.SMTP.Password, settings.SMTP.Server)
	}

	err := smtp.SendMail(settings.SMTP.Server+":"+settings.SMTP.Port, auth, settings.SMTP.Username, message.Recipients, []byte(email))
	if err != nil {
		log.Println(err)
		return err
	}

	return nil
}
