package main

import (
	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
	"log"
	"regexp"
	"strings"
	"time"
	"watn3y/bloaterbotv3/botIO"
	"watn3y/bloaterbotv3/commonlogic"
	"watn3y/bloaterbotv3/config"
	"watn3y/bloaterbotv3/text/nhentai"
)

var shutuptime time.Time

func bot() {
	updates, bot := botIO.Authenticate()

	for update := range updates {
		if update.Message == nil {
			continue
		}

		if update.Message.IsCommand() {
			go commands(update, bot)
		} else {
			if time.Since(shutuptime).Minutes() >= 60 {
				go textMatcher(update, bot)
			}

		}

	}
}

func textMatcher(update tgbotapi.Update, bot *tgbotapi.BotAPI) {

	//nhentai
	const nhentaiRegex string = "([ \\t\\n\\r]|^)\\d{2,}([ \\t\\n\\r]|$)"
	isNhentai, err := regexp.MatchString(nhentaiRegex, update.Message.Text)
	if err != nil {
		log.Panicf("Failed to compile regex for nhentai", err)
	}
	if isNhentai && commonlogic.ContainsInt64(config.BotConfig.Nhentai.EnabledChats, update.Message.Chat.ID) {
		go nhentai.Nhentai(nhentaiRegex, update, bot)
	}

	//balonlyl
	var isBalonlyl bool = false
	for _, word := range config.BotConfig.Balonlyl.TriggerWords {
		if strings.Contains(strings.ToLower(update.Message.Text), word) && commonlogic.ContainsInt64(config.BotConfig.Balonlyl.EnabledChats, update.Message.Chat.ID) {
			isBalonlyl = true
			break
		}
	}
	if isBalonlyl {
		go balonlyl(update, bot)
	}

}

func commands(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
	if strings.ToLower(update.Message.Command()) == "shutup" || strings.ToLower(update.Message.Command()) == "shut" {
		shutuptime = time.Now().UTC()

		msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Shutting up")
		botIO.SendMessage(msg, bot)
	}
}