package commands

import (
	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
	"github.com/rs/zerolog/log"
	"os"
	"strconv"
	"strings"
	"time"
	"watn3y/bloaterbotv3/botIO"
	"watn3y/bloaterbotv3/commands/download"
	"watn3y/bloaterbotv3/commands/gaypoints"
	"watn3y/bloaterbotv3/commands/notify"
	"watn3y/bloaterbotv3/config"
)

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

	cmd := strings.ToLower(update.Message.Command())

	log.Debug().Str("cmd", cmd).Msg("Matching command")

	switch cmd {
	case "shutup":
		shutup(update, bot)
	case "shut":
		shutup(update, bot)
	case "gp":
		gaypoints.GetGP(update, bot)
	case "addgp":
		gaypoints.SetGP(update, bot)
	case "subtractgp":
		gaypoints.SetGP(update, bot)
	case "remindme":
		notify.Reminder(update, bot)
	case "download":
		go download.Download(update, bot)
	case "dl":
		go download.Download(update, bot)
	case "help":
		help(update, bot)
	case "info":
		info(update, bot)
	}
}

func shutup(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
	config.BotConfig.Shutup[update.Message.Chat.ID] = time.Now().UTC()
	msg := tgbotapi.NewMessage(update.Message.Chat.ID, "Shutting up")

	log.Info().Int64("chat", update.Message.Chat.ID).Msg("Shutting up")

	botIO.SendMessage(msg, bot)

}

func help(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
	const textHelp string = "<b>User commands:</b>" + "\n\n" +
		"<code>/help </code><i>Sends this help message</i>" + "\n" +
		"<code>/gp </code><i>List Gaypoints for user or group</i>" + "\n" +
		"<code>/remindme 2m,5h,7d &lt;message&gt; </code> <i>Send a reminder message in 2 minutes, 5 hours, 7 days</i>" + "\n\n" +
		"<b>Admin Commands:</b>" + "\n" +
		"<code>/addgp &lt;amount&gt; </code>   <i>Add Gaypoints to User</i>" + "\n" +
		"<code>/subtractgp &lt;amount&gt; </code>   <i>Add Gaypoints to User</i>" + "\n"

	message := tgbotapi.MessageConfig{
		BaseChat:              tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID},
		ParseMode:             "html",
		DisableWebPagePreview: false,
		Text:                  textHelp,
	}
	botIO.SendMessage(message, bot)

}

func info(update tgbotapi.Update, bot *tgbotapi.BotAPI) {
	me, _ := bot.GetMe()
	commit := os.Getenv("COMMIT")
	if commit == "" {
		commit = "not available"
	}
	info, _ := os.Stat("./bloater.db")
	dbSizeInKiloBytes := info.Size() / 1000

	textInfo := "<b>" + me.FirstName + "</b>" + "\n\n" +
		"<b>Commit:</b> " + "<code>" + commit + "</code>" + "\n" +
		"<b>DB Size:</b> " + "<code>" + strconv.FormatInt(dbSizeInKiloBytes, 10) + "KB" + "</code>"

	message := tgbotapi.MessageConfig{
		BaseChat:              tgbotapi.BaseChat{ChatID: update.Message.Chat.ID, ReplyToMessageID: update.Message.MessageID},
		ParseMode:             "html",
		DisableWebPagePreview: false,
		Text:                  textInfo,
	}
	botIO.SendMessage(message, bot)

}