package api

import (
	"bytes"
	"crypto/tls"
	"errors"
	"html/template"

	gomail "gopkg.in/gomail.v2"
)

type Profile struct {
	Host     string `json:"host" bson:"host"`
	Usuario  string `json:"usuario" bson:"usuario"`
	Password string `json:"password" bson:"password"`
	Nome     string `json:"nome" bson:"nome"`
	Porta    int    `json:"porta" bson:"porta"`
}

type Message struct {
	gomail.Message
	Template string
	Context  interface{}
}

var (
	Serders = map[string]*Profile{}
)

func New() *Message {
	return &Message{Message: *gomail.NewMessage()}
}

func (t *Profile) GetFullNameAdrress() string {
	return t.Nome + " <" + t.Usuario + ">"
}

func RegisterSender(nome string, s *Profile) {
	Serders[nome] = s
}

func Sender(nome string) (*Profile, bool) {
	s, ok := Serders[nome]
	return s, ok
}

func Send(sender string, m *Message) error {
	var (
		s  *Profile
		ok bool
	)
	if s, ok = Sender(sender); !ok {
		return errors.New("Perfil '" + sender + "' não exites")
	}

	dialer := gomail.NewDialer(s.Host, s.Porta, s.Usuario, s.Password)
	dialer.TLSConfig = &tls.Config{InsecureSkipVerify: true}

	if err := m.parseTemplate(); err != nil {
		return err
	}

	return dialer.DialAndSend(&m.Message)
}

func (t *Message) Send(sender string) error {
	return Send(sender, t)
}

func (t *Message) SetTemplate(filename string, ctx interface{}) {
	t.Template = filename
	t.Context = ctx
}

func (m *Message) parseTemplate() (err error) {
	var (
		t   *template.Template
		buf *bytes.Buffer
	)
	if m.Template == "" {
		return nil
	}

	if t, err = template.ParseFiles(m.Template); err != nil {
		return err
	}

	buf = new(bytes.Buffer)

	if err = t.Execute(buf, m.Context); err != nil {
		return err
	}

	m.SetBody("text/html", buf.String())

	return nil
}
