package beatleader

import (
	"log"
	"time"

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

const wsURL = "wss://sockets.api.beatleader.xyz/scores"

var BlScoresManager = blScoresManager{}

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

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

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

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

func (sm *blScoresManager) GetRecentScores(count int, predict string) []RecordDataLite {
	db := sqlite3.GetDB()
	scoresCopy := make([]RecordDataLite, 0, count)

	query := "SELECT * FROM blRecordData"
	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() {
	db := sqlite3.GetDB()
	ssBind := make([]string, 0)
	db.Select(&ssBind, "SELECT ssid FROM ssBind")
	db.Exec("DELETE FROM blRecordData WHERE generated_time < ? AND ssid NOT IN (?)", time.Now().AddDate(0, 0, -1).Unix(), ssBind)
}
