package tg

import (
	"time"

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

func Start() {
	MainBot := NewBot()

	event2.On(EventSendMsg, event2.ListenerFunc(MainBot.onSendMsg))

	go func() {
		<-time.After(3 * time.Second)

		go StartGameTimer()
		go GameStart()
	}()

	botToken := viper.GetString("bot_token")
	logrus.Fatal(MainBot.InitDebug(botToken))
}

type Bot struct {
	botApi        *tgbotapi.BotAPI
	updateChannel tgbotapi.UpdatesChannel
}

func NewBot() *Bot {
	return &Bot{}
}

func (p *Bot) onSendMsg(e event2.Event) error {
	logrus.Info("onSendMsg:", e)
	c := e.Get("msg").(tgbotapi.Chattable)
	resp, err := p.botApi.Send(c)
	if err != nil {
		logrus.Error(err)
		return nil
	}

	logrus.Info("send finish:", resp)

	return nil
}

func (p *Bot) InitDebug(token string) error {
	bot, err := tgbotapi.NewBotAPI(token)
	if err != nil {
		logrus.Fatal(err)
		return err
	}

	bot.Debug = true

	logrus.Infof("Authorized on account %s", bot.Self.UserName)
	delWebhookConfig := tgbotapi.DeleteWebhookConfig{
		DropPendingUpdates: true,
	}

	bot.Send(delWebhookConfig)

	hookCfg := tgbotapi.NewUpdate(0)

	hookCfg.AllowedUpdates = []string{tgbotapi.UpdateTypeChatMember, tgbotapi.UpdateTypeMessage,
		tgbotapi.UpdateTypeInlineQuery, tgbotapi.UpdateTypeCallbackQuery}

	bot.Debug = true

	p.botApi = bot
	p.updateChannel = bot.GetUpdatesChan(hookCfg)

	p.ProcNewMessage()
	return nil
}

func (p *Bot) Init(token string) error {
	bot, err := tgbotapi.NewBotAPI(token)
	if err != nil {
		logrus.Fatal(err)
		return err
	}

	bot.Debug = false

	logrus.Infof("Authorized on account %s", bot.Self.UserName)

	basePath := viper.GetString("base_path") // "/api/botzhenren"
	fullPath := "http://13.214.75.66:1180" + basePath
	if !viper.GetBool("is_debug") {
		fullPath = "https://prodcpbot.daxia.dev" + basePath
	}

	hookCfg, err := tgbotapi.NewWebhook(fullPath)
	if err != nil {
		logrus.Fatal(err)
	}

	hookCfg.AllowedUpdates = []string{tgbotapi.UpdateTypeChatMember, tgbotapi.UpdateTypeMessage,
		tgbotapi.UpdateTypeInlineQuery, tgbotapi.UpdateTypeCallbackQuery}

	_, err = bot.Request(hookCfg)
	if err != nil {
		logrus.Fatal(err)
	}

	info, err := bot.GetWebhookInfo()
	if err != nil {
		logrus.Fatal(err)
	}

	if info.LastErrorDate != 0 {
		logrus.Printf("Telegram callback failed: %s", info.LastErrorMessage)
	}

	p.updateChannel = bot.ListenForWebhook(basePath)

	p.botApi = bot
	p.ProcNewMessage()

	return nil
}

func (p *Bot) GetBotApi() *tgbotapi.BotAPI {
	return p.botApi
}

func (p *Bot) ProcNewMessage() {
	if p.updateChannel == nil {
		logrus.Error("updata channel is nil")
		return
	}

	for update := range p.updateChannel {
		logrus.Info("recv update msg:", update)
		go event2.MustFire(EventUpdateMsg, event2.M{
			"update": update,
		})
	}
}
