package tgbot

import (
	"fmt"
	"log"
	"net/http"
	"net/url"
	"tg-mc/conf"
	"tg-mc/models"
	"tg-mc/services/utils"

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

func Run(sendFunc func(string)) {
	var err error

	HttpProxy := conf.GetBotSettings().HTTPProxy
	proxyUrl, err := url.Parse(HttpProxy)
	if err != nil {
		log.Panic(err, "HTTP_PROXY environment variable is not set correctly")
	}

	client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyUrl)}}
	conf.Bot, err = tgbotapi.NewBotAPIWithClient(
		conf.GetBotSettings().BotToken,
		// tgbotapi.APIEndpoint,
		conf.GetBotSettings().TGBotApi,
		client)

	if err != nil {
		log.Panic(err)
	}

	conf.Bot.Debug = false

	log.Printf("Authorized on account %s", conf.Bot.Self.UserName)

	u := tgbotapi.NewUpdate(0)
	u.Timeout = 60
	updates := conf.Bot.GetUpdatesChan(u)

	for update := range updates {
		if update.Message != nil {
			go func(m *tgbotapi.Message) {
				logrus.Infof("[%s] %s", m.From.UserName, m.Text)
				if m.Command() == "talk" {
					logrus.Infof("id is %d", m.Chat.ID)
					m := fmt.Sprintf("%v: %v", m.From.UserName, m.CommandArguments())
					sendFunc(m)
					logrus.WithError(err).Error("send message error")
					return
				}
				if m.Command() == "list" {
					logrus.Infof("id is %d", m.Chat.ID)
					m := tgbotapi.NewMessage(m.Chat.ID, utils.GetAlivePlayer())
					conf.Bot.Send(m)
					return
				}
				if m.Command() == "bind" {
					logrus.Infof("id is %d", m.Chat.ID)
					err := models.CreateUser(&models.User{
						TGID:   m.From.ID,
						MCName: m.CommandArguments(),
						Status: 1,
					})
					if err != nil {
						m := tgbotapi.NewMessage(m.Chat.ID, "绑定失败, err: "+err.Error())
						conf.Bot.Send(m)
						return
					}
					m := tgbotapi.NewMessage(m.Chat.ID,
						fmt.Sprintf("绑定成功,你的MCID是%v", m.CommandArguments()))
					conf.Bot.Send(m)
					return
				}
				if m.Command() == "unbind" {
					logrus.Infof("id is %d", m.Chat.ID)
					u, err := models.GetUserByTGID(m.From.ID)
					if err != nil {
						m := tgbotapi.NewMessage(m.Chat.ID, "你还没有绑定")
						conf.Bot.Send(m)
						return
					}
					err = u.Delete(m.From.ID)
					if err != nil {
						m := tgbotapi.NewMessage(m.Chat.ID, "解绑失败")
						conf.Bot.Send(m)
						return
					}
					m := tgbotapi.NewMessage(m.Chat.ID, "解绑成功")
					conf.Bot.Send(m)
					return
				}
				if m.Command() == "get" {
					logrus.Infof("id is %d", m.Chat.ID)
					u, err := models.GetUserByTGID(m.From.ID)
					if err != nil {
						m := tgbotapi.NewMessage(m.Chat.ID, "你还没有绑定")
						conf.Bot.Send(m)
						return
					}
					m := tgbotapi.NewMessage(m.Chat.ID, fmt.Sprintf("你的MCID是%v", u.MCName))
					conf.Bot.Send(m)
					return
				}
			}(update.Message)
		}
	}
}