package tg

import (
	"fmt"
	"sync/atomic"

	tgbotapi "github.com/go-telegram-bot-api/telegram-bot-api/v5"
	"github.com/sirupsen/logrus"
)

var index = int32(30)
var idMap = map[int64]int32{}

func GameStart() {
	event2.On(EventUpdateMsg, event2.ListenerFunc(onUpdate))
}

func onUpdate(e event2.Event) error {
	var err error

	update := e.Get("update").(tgbotapi.Update)

	// if update.Message != nil {
	// 	if update.Message.Text == "yx" {
	// 		sendGameInfo()
	// 	}
	// 	return nil
	// }

	if update.CallbackQuery == nil {
		logrus.Info("CallbackQuery is null")
		return nil
	}

	//shortName := viper.GetString("short_name")
	currIndex := int32(0)
	indexVal, exists := idMap[update.CallbackQuery.From.ID]
	if !exists {
		index = atomic.AddInt32(&index, 1)
		currIndex = index
	} else {
		currIndex = indexVal
	}

	idMap[update.CallbackQuery.From.ID] = currIndex

	logrus.Info("shortname: ", update.CallbackQuery.GameShortName)
	if update.CallbackQuery.GameShortName == "qznn" {
		gameConfig := tgbotapi.CallbackConfig{
			CallbackQueryID: update.CallbackQuery.ID,
			URL:             fmt.Sprintf("https://211.99.98.167:3306/web-desktopQZNN/index.html?tk=8bc766ae05120ad091e8e52c29e23c%d&app=1", currIndex),
			CacheTime:       0,
		}

		logrus.Info("gameconfig:", gameConfig)
		go event2.MustFire(EventSendMsg, event2.M{
			"msg": gameConfig,
		})

		return nil
	}

	logrus.Error("not found game")
	return err
}
