package utils

import (
	"bytes"
	"exhibitionCentre/config"
	"exhibitionCentre/logging"
	"text/template"

	"gopkg.in/gomail.v2"
)

func SendVerificationCode(address, code string) bool {
	tmp, err := template.ParseFiles("./view/html/verification_code.html")
	if err != nil {
		logging.Log.Errorf("读取验证码邮件模板失败: %s\n", err.Error())
		return false
	}

	var buf bytes.Buffer
	tmp.Execute(&buf, code)

	return SendEmail(address, "验证码", buf.String())
}

func SendInvitationEmail(address string) bool {
	tmp, err := template.ParseFiles("./view/html/invitation.html")
	if err != nil {
		logging.Log.Errorf("读取邀请邮件模板失败: %s\n", err.Error())
		return false
	}

	var buf bytes.Buffer
	tmp.Execute(&buf, config.Config.Others.LoginUrl)

	return SendEmail(address, "邀请邮件", buf.String())
}

func SendEmail(toAdress, subject, body string) bool {
	from := config.Config.Smtp.FromEmail
	m := gomail.NewMessage()
	m.SetHeader("From", from)
	m.SetHeader("To", toAdress)
	m.SetHeader("Subject", subject)
	m.SetBody("text/html", body)

	host := config.Config.Smtp.Host
	port := config.Config.Smtp.Port
	username := config.Config.Smtp.UserName
	password := config.Config.Smtp.Password
	d := gomail.NewDialer(host, port, username, password)

	// Send the email to Bob, Cora and Dan.
	if err := d.DialAndSend(m); err != nil {
		logging.Log.Errorf("发送邮件失败: %s\n", err.Error())
		return false
	}
	return true
}
