package client

import (
	"log/slog"
	"math/rand"
	"strconv"
	"strings"
	textTemplate "text/template"

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

	"github.com/Masterminds/sprig/v3"

	"git.sr.ht/~ashkeel/strimertul/twitch/template"

	"github.com/nicklaw5/helix/v2"
)

const ChatCounterPrefix = "twitch/chat/counters/"

type templateEngineImpl struct {
	customFunctions textTemplate.FuncMap
}

func (b *templateEngineImpl) MakeTemplate(message string) (*textTemplate.Template, error) {
	return textTemplate.New("").Funcs(sprig.TxtFuncMap()).Funcs(b.customFunctions).Parse(message)
}

func (c *Client) GetTemplateEngine() template.Engine {
	return &templateEngineImpl{
		customFunctions: textTemplate.FuncMap{
			"user": func(message helix.EventSubChannelChatMessageEvent) string {
				return message.ChatterUserLogin
			},
			"param": func(num int, message helix.EventSubChannelChatMessageEvent) string {
				parts := strings.Split(message.Message.Text, " ")
				if num >= len(parts) {
					return parts[len(parts)-1]
				}
				return parts[num]
			},
			"randomInt": func(min int, max int) int {
				return rand.Intn(max-min) + min
			},
			"game": func(channel string) string {
				channel = strings.TrimLeft(channel, "@")
				info, err := c.API.SearchChannels(&helix.SearchChannelsParams{Channel: channel, First: 1, LiveOnly: false})
				if err != nil {
					return "unknown"
				}
				return info.Data.Channels[0].GameName
			},
			"count": func(name string) int {
				counterKey := ChatCounterPrefix + name
				counter := 0
				if byt, err := c.DB.GetKey(counterKey); err == nil {
					counter, _ = strconv.Atoi(byt)
				}
				counter++
				err := c.DB.PutKey(counterKey, strconv.Itoa(counter))
				if err != nil {
					c.Logger.Error("Error saving key", slog.String("key", counterKey), log.Error(err))
				}
				return counter
			},
		},
	}
}
