package tgbot

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

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

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

	api := conf.GetBotSettings().BotAPI
	if len(api) == 0 {
		api = tgbotapi.APIEndpoint
	}

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

	if len(HttpProxy) != 0 {
		client := &http.Client{Transport: &http.Transport{Proxy: http.ProxyURL(proxyUrl)}}
		conf.Bot, err = tgbotapi.NewBotAPIWithClient(
			conf.GetBotSettings().BotToken,
			api,
			client)
	} else {
		conf.Bot, err = tgbotapi.NewBotAPIWithAPIEndpoint(conf.GetBotSettings().BotToken, api)
	}

	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" {
					if !utils.IsAdmin(m) &&
						len(m.CommandArguments()) != 0 {
						tm := tgbotapi.NewMessage(m.Chat.ID, "您不是管理员,没有该权限")
						conf.Bot.Send(tm)
						return
					} else if utils.IsAdmin(m) &&
						len(m.CommandArguments()) != 0 {
						a := commonUtils.GetArgs(m.CommandArguments())
						if len(a) != 2 {
							tm := tgbotapi.NewMessage(m.Chat.ID, "参数错误,样例:\n```\n/get <tgid|username> <value>\n```")
							tm.ParseMode = "Markdown"
							conf.Bot.Send(tm)
							return
						}
						if a[0] == "tgid" {
							tgid, err := strconv.ParseInt(a[1], 10, 64)
							if err != nil {
								conf.Bot.Send(tgbotapi.NewMessage(m.Chat.ID, "ID错误,应该为int64"))
								return
							}
							u, err := models.GetUserByTGID(tgid)
							if err != nil {
								tm := tgbotapi.NewMessage(m.Chat.ID, fmt.Sprintf("查询出错,err:\n```\n%+v\n```", err))
								tm.ParseMode = "Markdown"
								conf.Bot.Send(tm)
								return
							}
							tm := tgbotapi.NewMessage(m.Chat.ID, fmt.Sprintf("用户信息:\n```\n%+v\n```", u))
							tm.ParseMode = "Markdown"
							conf.Bot.Send(tm)
						}
						if a[0] == "username" {
							u, err := models.GetUserByMCName(a[1])
							if err != nil {
								tm := tgbotapi.NewMessage(m.Chat.ID, fmt.Sprintf("查询出错,err:\n```\n%+v\n```", err))
								tm.ParseMode = "Markdown"
								conf.Bot.Send(tm)
								return
							}
							tm := tgbotapi.NewMessage(m.Chat.ID, fmt.Sprintf("用户信息:\n```\n%+v\n```", u))
							tm.ParseMode = "Markdown"
							conf.Bot.Send(tm)
						}
						return
					}
					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
				}
				if m.Command() == "set" {
					if !utils.IsAdmin(m) {
						tm := tgbotapi.NewMessage(m.Chat.ID, "您不是管理员,没有该权限")
						conf.Bot.Send(tm)
						return
					}
					a := commonUtils.GetArgs(m.CommandArguments())
					if len(a) != 3 {
						tm := tgbotapi.NewMessage(m.Chat.ID, "参数错误,样例:\n```\n/set username tgid status\n```")
						tm.ParseMode = "Markdown"
						conf.Bot.Send(tm)
						return
					}
					tgid, err := strconv.ParseInt(a[1], 10, 64)
					if err != nil {
						conf.Bot.Send(tgbotapi.NewMessage(m.Chat.ID, "ID错误,应该为int64"))
						return
					}
					status, err := strconv.ParseInt(a[2], 10, 64)
					if err != nil || !lo.Contains([]int64{0, 1, 2}, status) {
						conf.Bot.Send(tgbotapi.NewMessage(m.Chat.ID, "Status错误,应该为0(Pending),1(Normal),2(Banned)"))
						return
					}
					if err := models.CreateUser(&models.User{
						TGID:   tgid,
						MCName: a[0],
						Status: int(status),
					}); err != nil {
						tm := tgbotapi.NewMessage(m.Chat.ID, fmt.Sprintf("创建用户错误,err:\n```\n%+v\n```", err))
						tm.ParseMode = "Markdown"
						conf.Bot.Send(tm)
						return
					}
					conf.Bot.Send(tgbotapi.NewMessage(m.Chat.ID, "设置用户成功"))
					return
				}
			}(update.Message)
		}
	}
}