package alerts

import (
	"bytes"
	"text/template"

	"git.sr.ht/~ashkeel/strimertul/log"

	"git.sr.ht/~ashkeel/strimertul/twitch/chat"
)

func (m *Module) compileTemplates() {
	// Reset caches
	m.templates = templateCacheMap{
		templateTypeSubscription: make(templateCache),
		templateTypeFollow:       make(templateCache),
		templateTypeRaid:         make(templateCache),
		templateTypeCheer:        make(templateCache),
		templateTypeGift:         make(templateCache),
	}

	// Add base templates
	m.addTemplatesForType(templateTypeFollow, m.Config.Follow.Messages)
	m.addTemplatesForType(templateTypeSubscription, m.Config.Subscription.Messages)
	m.addTemplatesForType(templateTypeRaid, m.Config.Raid.Messages)
	m.addTemplatesForType(templateTypeCheer, m.Config.Cheer.Messages)
	m.addTemplatesForType(templateTypeGift, m.Config.GiftSub.Messages)

	// Add variations
	for _, variation := range m.Config.Subscription.Variations {
		m.addTemplatesForType(templateTypeSubscription, variation.Messages)
	}
	for _, variation := range m.Config.Raid.Variations {
		m.addTemplatesForType(templateTypeRaid, variation.Messages)
	}
	for _, variation := range m.Config.Cheer.Variations {
		m.addTemplatesForType(templateTypeCheer, variation.Messages)
	}
	for _, variation := range m.Config.GiftSub.Variations {
		m.addTemplatesForType(templateTypeGift, variation.Messages)
	}
}

func (m *Module) addTemplate(templateList templateCache, message string) {
	tpl, err := m.templater.MakeTemplate(message)
	if err != nil {
		m.logger.Error("Error compiling alert template", log.Error(err))
		return
	}
	templateList[message] = tpl
}

func (m *Module) addTemplatesForType(templateList templateType, messages []string) {
	for _, message := range messages {
		m.addTemplate(m.templates[templateList], message)
	}
}

// writeTemplate renders the template and sends the message to the channel
func (m *Module) writeTemplate(tpl *template.Template, data interface{}, announce bool) {
	var buf bytes.Buffer
	if err := tpl.Execute(&buf, data); err != nil {
		m.logger.Error("Error executing template for bot alert", log.Error(err))
		return
	}
	chat.WriteMessage(m.db, m.logger, chat.WriteMessageRequest{
		Message:  buf.String(),
		Announce: announce,
	})
}
