package scoresaber

import (
	"log"
	"strconv"

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

func init() {
	handler.RegisterHandler("查ss", getMySS)
	handler.RegisterHandler("绑定ss", bindSS)
	handler.RegisterHandler("解绑ss", unbindSS)
	handler.RegisterHandler("最新ss", getMyRecentScore)
	handler.RegisterHandler("最热ss", getRecentScore)
	handler.RegisterHandler("截图ss", screenshotSS)
}

func getMySS(msg model.Message) (reply model.Reply) {
	var (
		resultStr  string
		err        error
		maxRetries = 3 // 最大重试次数
		attempts   = 0
	)

	userIdStr := strconv.Itoa(int(msg.UserId))
	for attempts < maxRetries {
		resultStr, err = scoresaber.SSQuery.GetScore(userIdStr)
		if err == nil {
			break // 成功时退出循环
		}
		attempts++
		log.Printf("获取分数时出错，第 %d 次重试: %v", attempts, err)
	}

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

	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.Msg[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.Msg) > len("最热ss ") {
		var err error
		count, err = strconv.Atoi(msg.Msg[len("最热ss "):])
		if err != nil || count <= 0 {
			return model.Reply{
				ReplyMsg:       "",
				ReferOriginMsg: true,
				FromMsg:        msg,
			}
		}
	}
	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.Msg) > len("最新ss ") {
		var err error
		count, err = strconv.Atoi(msg.Msg[len("最新ss "):])
		if err != nil || count <= 0 {
			return model.Reply{
				ReplyMsg:       "",
				ReferOriginMsg: true,
				FromMsg:        msg,
			}
		}
	}
	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:///root/qqbot/tmp/" + scoresaber.GetSSPicture(strconv.Itoa(int(msg.UserId))) + "]",
		ReferOriginMsg: true,
		FromMsg:        msg,
	}
}
