package auth

import (
	"log"
	"time"

	"code.secondbit.org/events.hg"
)

const (
	EventSystem                 = "authd"
	EventModelLogin             = "login"
	EventActionSendVerification = "send_verification"
	EventTopicLoginVerification = "login_verification"
)

type loginVerificationNotifier interface {
	SendLoginVerification(login Login)
}

type stdoutNotifier struct{}

func NewStdoutNotifier() stdoutNotifier {
	return stdoutNotifier{}
}

func (s stdoutNotifier) SendLoginVerification(login Login) {
	log.Printf("Use \"%s\" as the verification code for \"%s\"\n", login.Verification, login.Value)
}

type nsqNotifier struct {
	*events.NSQPublisher
}

func NewNSQNotifier(address string) (*nsqNotifier, error) {
	p, err := events.NewNSQPublisher(EventSystem+"/"+Version, address)
	return &nsqNotifier{p}, err
}

func (n *nsqNotifier) SendLoginVerification(login Login) {
	evt := events.Event{
		System:    EventSystem,
		Model:     EventModelLogin,
		ID:        login.Value,
		Action:    EventActionSendVerification,
		Timestamp: time.Now(),
		Data: map[string]string{
			"verification": login.Verification,
		},
	}
	err := n.Publish(EventTopicLoginVerification, evt)
	if err != nil {
		log.Printf("Error sending event: %#+v\n", err)
	}
}
