package scoresaber

import (
	"log"
	"time"

	"git.lxtend.com/qqbot/sqlite3"
	"git.lxtend.com/qqbot/util"
	"github.com/gorilla/websocket"
)

const wsURL = "wss://scoresaber.com/ws"

var ScoresManager = scoresManager{}

type scoresManager struct {
	conn       *websocket.Conn
	retryTimes int
}

func init() {
	for err := ScoresManager.connect(); err != nil; err = ScoresManager.connect() {
		log.Print("连接 WebSocket 失败:", err)
		time.Sleep(time.Second)
	}
	util.AddCycleTask("cleanOldScores", 0, 1*time.Hour, cleanOldScores)
}

func (sm *scoresManager) connect() error {
	var err error
	sm.conn, _, err = websocket.DefaultDialer.Dial(wsURL, nil)
	if err != nil {
		return err
	}
	sm.retryTimes = 0
	go sm.receiveData()
	return nil
}

func (sm *scoresManager) receiveData() {
	defer func() {
		for err := ScoresManager.connect(); err != nil; err = ScoresManager.connect() {
			log.Printf("连接 WebSocket 失败:%v", err)
			time.Sleep(time.Second)
		}
	}()
	for {
		var cmd Command
		err := sm.conn.ReadJSON(&cmd)
		if err != nil {
			log.Print("读取数据失败:", err)
			time.Sleep(time.Second)
			sm.retryTimes++
			if sm.retryTimes > 3 {
				return
			}
			continue
		}
		SSQuery.SaveRecord(cmd.CommandData)
	}
}

func (sm *scoresManager) GetRecentScores(count int, predict string) []RecordDataLite {
	db := sqlite3.GetDB() // 假设 sqlite3.GetDB() 返回 *sqlx.DB
	scoresCopy := make([]RecordDataLite, 0, count)

	query := "SELECT * FROM ssRecordData"
	if predict != "" {
		query += " " + predict
	}
	query += " ORDER BY generated_time DESC LIMIT ?"

	err := db.Select(&scoresCopy, query, count)
	if err != nil {
		log.Print(err)
		return nil
	}

	return scoresCopy
}

func cleanOldScores() {
	//清除>1天前且未绑定ss的记录
	//1.获取所有绑定ss
	//2.获取所有>1天前的记录
	//3.删除未绑定ss的记录
	db := sqlite3.GetDB()
	ssBind := make([]string, 0)
	db.Select(&ssBind, "SELECT ssid FROM ssBind")
	db.Exec("DELETE FROM ssRecordData WHERE generated_time < ? AND ssid NOT IN (?)", time.Now().AddDate(0, 0, -1).Unix(), ssBind)
}
