package postman

import (
	"bytes"
	"errors"
	"net/smtp"
	"strconv"
	"strings"
	"time"
)

// SMTP сервис
type Service struct {
	user     string
	password string
	host     string
	port     int
}

func NewService(host string, port int, sender string, password string) *Service {
	return &Service{
		user:     sender,
		password: password,
		host:     host,
		port:     port,
	}
}

// Отправка письма
func (s *Service) Send(message Message) error {
	if len(message.to) < 1 {
		return errors.New("empty list of recipients")
	}

	//
	auth := smtp.PlainAuth("", s.user, s.password, s.host)

	//
	buffer := bytes.NewBuffer(nil)
	boundary := "GoBoundary"
	headery := ""

	// header
	header := make(map[string]string)
	header["From"] = s.user

	header["To"] = message.to[0]
	header["Cc"] = strings.Join(message.to[1:], ";")
	header["Subject"] = message.subject
	header["Content-Type"] = "multipart/mixed;boundary=" + boundary
	header["Mime-Version"] = "1.0"
	header["Date"] = time.Now().String()

	for key, value := range header {
		headery += key + ":" + value + "\r\n"
	}

	buffer.WriteString(headery + "\r\n")

	// body
	body := "\r\n--" + boundary + "\r\n"
	body += "Content-Type:" + message.contentType + "\r\n"
	body += "\r\n" + message.body + "\r\n"

	buffer.WriteString(body)

	// attachments
	for _, x := range message.attachments {
		if x.withFile {
			attachment := "\r\n--" + boundary + "\r\n"
			attachment += "Content-Transfer-Encoding:base64\r\n"
			attachment += "Content-Disposition:attachment\r\n"
			attachment += "Content-Type:" + x.contentType + ";name=\"" + x.name + "\"\r\n"

			//
			buffer.WriteString(attachment)

			//
			x.WriteFile(buffer)
		}
	}

	buffer.WriteString("\r\n--" + boundary + "--")

	// Sending message
	return smtp.SendMail(s.host+":"+strconv.Itoa(s.port), auth, s.user, message.to, buffer.Bytes())
}