package hooks

import (
	"fmt"

	"github.com/sirupsen/logrus"
)

var linkClient *Client

type NotificationHook struct {
	Project     *Project
	Maintainers []*Maintainer
	NS          *NotificationService
}

type Project struct {
	Name   string
	Domain string
}

type Maintainer struct {
	Name  string
	Email string
}

type NotificationService struct {
	Addr string
	Port int
}

func DefaultMaintainers() []*Maintainer {
	return []*Maintainer{
		{
			Name:  "Paul",
			Email: "paul@links123.com",
		},
		{
			Name:  "Adam",
			Email: "adam@links123.com",
		},
		{
			Name:  "Whao",
			Email: "whao@links123.com",
		},
		{
			Name:  "Slate",
			Email: "slate@links123.com",
		},
	}
}

func DefaultNotificationService() *NotificationService {
	return &NotificationService{
		Addr: "127.0.0.1",
		Port: 8085,
	}
}

func (nh *NotificationHook) Fire(entry *logrus.Entry) error {
	return notify(nh, entry)
}

func (nh *NotificationHook) Levels() []logrus.Level {
	return []logrus.Level{
		logrus.ErrorLevel,
		logrus.FatalLevel,
		logrus.PanicLevel,
	}
}

func NewNotificationHook(project *Project, maintainers []*Maintainer, ns *NotificationService) (*NotificationHook, error) {
	if project == nil {
		return nil, fmt.Errorf("project is required")
	}
	if maintainers == nil {
		return nil, fmt.Errorf("maintainers muest not be blank")
	}
	if ns == nil {
		return nil, fmt.Errorf("notification service is required")
	}

	if linkClient == nil {
		linkClient = NewClient(ns.Addr, ns.Port)
	}

	return &NotificationHook{Project: project, Maintainers: maintainers, NS: ns}, nil
}

func notify(nh *NotificationHook, entry *logrus.Entry) error {
	var emails []string
	for _, m := range nh.Maintainers {
		emails = append(emails, m.Email)
	}
	_, err := defaultClient.Notify(&NotifyRequest{
		Project:     nh.Project.Name,
		Maintainers: emails,
		Message:     entry.Message,
		Time:        entry.Time.Format("2006-02-01 15:04:05"),
	})
	return err
}
