package scoresaber

import (
	"log"
	"time"

	"git.lxtend.com/qqbot/sqlite3"
	"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)
	}
}

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
}
