package scoresaber

import (
	"log"
	"strconv"
	"strings"

	"git.lxtend.com/qqbot/constants"
	"git.lxtend.com/qqbot/handler"
	"git.lxtend.com/qqbot/model"
	"git.lxtend.com/qqbot/service/scoresaber"
)

func init() {
	handler.RegisterHandler("查ss", getSSProfile, constants.LEVEL_USER)
	handler.RegisterHelpInform("查ss", "scoresaber", "	查看您的最新分数")
	handler.RegisterHandler("绑定ss", bindSS, constants.LEVEL_USER)
	handler.RegisterHelpInform("绑定ss", "scoresaber", "绑定您的scoresaber账号")
	handler.RegisterHandler("解绑ss", unbindSS, constants.LEVEL_USER)
	handler.RegisterHelpInform("解绑ss", "scoresaber", "解绑您的scoresaber账号")
	handler.RegisterHandler("最新ss", getMyRecentScore, constants.LEVEL_USER)
	handler.RegisterHelpInform("最新ss", "scoresaber", "查看您的最新游戏记录")
	handler.RegisterHandler("最热ss", getRecentScore, constants.LEVEL_USER)
	handler.RegisterHelpInform("最热ss", "scoresaber", "查看全大陆的最新游戏记录")
	handler.RegisterHandler("截ss", screenshotSS, constants.LEVEL_USER)
	handler.RegisterHelpInform("截ss", "scoresaber", "scoresaber主页截图")
	handler.RegisterHandler("jss", screenshotSS, constants.LEVEL_USER)
}

func getSSProfile(msg model.Message) (reply model.Reply) {
	var (
		resultStr  string
		err        error
		maxRetries = 5 // 最大重试次数
		attempts   = 0
		noUpdate   = false
	)
	var ssId string
	if len(msg.RawMsg) > len("查ss ") {
		// ssId = msg.RawMsg[len("查ss "):]
		ssId = strings.Split(msg.RawMsg, " ")[1]
		noUpdate = true
	}

	userIdStr := strconv.Itoa(int(msg.UserId))
	for attempts < maxRetries {
		err = nil
		if ssId == "" {
			ssId, err = scoresaber.GetSSID(userIdStr)
		}
		if err != nil {
			// return "您未绑定ss账号，输入\"绑定ss [ssId]\"绑定", nil
			return model.Reply{
				ReplyMsg:       "您未绑定ss账号，输入\"绑定ss [ssId]\"绑定",
				ReferOriginMsg: true,
				FromMsg:        msg,
			}
		}
		if !noUpdate {
			resultStr, err = scoresaber.SSQuery.GetScore(ssId)
		} else {
			resultStr, err = scoresaber.SSQuery.GetScoreWithoutUpdate(ssId)
		}
		if err == nil {
			break // 成功时退出循环
		}
		attempts++
		log.Printf("获取分数时出错，第 %d 次重试: %v", attempts, err)
	}

	// 如果所有尝试都失败，返回适当的错误消息
	if err != nil {
		resultStr = "获取您的分数时出现问题，请稍后重试。" + err.Error()
	}

	return model.Reply{
		ReplyMsg:       resultStr,
		ReferOriginMsg: true,
		FromMsg:        msg,
	}
}

func bindSS(msg model.Message) (reply model.Reply) {
	return model.Reply{
		ReplyMsg:       scoresaber.SSQuery.BindSS(strconv.Itoa(int(msg.UserId)), msg.RawMsg[len("绑定ss "):]),
		ReferOriginMsg: true,
		FromMsg:        msg,
	}
}

func unbindSS(msg model.Message) (reply model.Reply) {
	return model.Reply{
		ReplyMsg:       scoresaber.SSQuery.UnbindSS(strconv.Itoa(int(msg.UserId))),
		ReferOriginMsg: true,
		FromMsg:        msg,
	}
}

func getRecentScore(msg model.Message) (reply model.Reply) {
	count := 1
	if len(msg.RawMsg) > len("最热ss ") {
		var err error
		count, err = strconv.Atoi(msg.RawMsg[len("最热ss "):])
		if err != nil || count <= 0 {
			return model.Reply{
				ReplyMsg:       "",
				ReferOriginMsg: true,
				FromMsg:        msg,
			}
		}
		if count > 10 {
			count = 10
		}
	}
	scoreMsg := ""
	for _, v := range scoresaber.ScoresManager.GetRecentScores(count, " WHERE country = 'CN' ") {
		scoreMsg += v.ToString() + "\n\n"
	}
	if len(scoreMsg) > 0 {
		scoreMsg = scoreMsg[:len(scoreMsg)-len("\n\n")]
	}
	return model.Reply{
		ReplyMsg:       scoreMsg,
		ReferOriginMsg: true,
		FromMsg:        msg,
	}
}

func getMyRecentScore(msg model.Message) (reply model.Reply) {
	count := 1
	scoreMsg := ""
	if len(msg.RawMsg) > len("最新ss ") {
		var err error
		count, err = strconv.Atoi(msg.RawMsg[len("最新ss "):])
		if err != nil || count <= 0 {
			return model.Reply{
				ReplyMsg:       "",
				ReferOriginMsg: true,
				FromMsg:        msg,
			}
		}
		if count > 10 {
			count = 10
		}
	}
	var userName string
	recordCount := 0
	records, err := scoresaber.SSQuery.GetRecentScores(count, strconv.Itoa(int(msg.UserId)))
	if err != nil {
		return model.Reply{
			ReplyMsg:       err.Error(),
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}
	for _, v := range records {
		scoreMsg += v.ToString() + "\n\n"
		userName = v.Name
		recordCount++
	}
	if len(scoreMsg) > 0 {
		scoreMsg = scoreMsg[:len(scoreMsg)-len("\n\n")] //去掉最后一个换行符
	} else {
		return model.Reply{
			ReplyMsg:       "无最近游戏记录",
			ReferOriginMsg: true,
			FromMsg:        msg,
		}
	}
	return model.Reply{
		ReplyMsg:       "玩家 " + userName + " 的" + strconv.Itoa(recordCount) + "条最近记录为：\n" + scoreMsg,
		ReferOriginMsg: true,
		FromMsg:        msg,
	}
}

func screenshotSS(msg model.Message) (reply model.Reply) {
	return model.Reply{
		ReplyMsg:       "[CQ:image,file=file:///tmp/qqbot/" + scoresaber.GetSSPicture(strconv.Itoa(int(msg.UserId))) + "]",
		ReferOriginMsg: true,
		FromMsg:        msg,
	}
}
