package jrrp

import (
	"database/sql"
	"math"
	"math/rand"
	"time"

	"git.lxtend.com/lixiangwuxian/qqbot/sqlite3"
	"github.com/jmoiron/sqlx"
	_ "github.com/mattn/go-sqlite3"
)

// 初始化 SQLite 数据库
func initDB() {
	createTableSQL := `CREATE TABLE IF NOT EXISTS jrrp (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        qqid TEXT UNIQUE,
        date TEXT,
        rp_value INTEGER
    );`
	sqlite3.TryCreateTable(createTableSQL)
}

// 获取今天的日期
func getTodayFullDate() string {
	today := time.Now().Format("2006-01-02")
	return today
}

// 构造RP值
func rpValueConstructor() (string, int) {
	rand.Seed(time.Now().UnixNano())
	rpValue := int(math.Floor(math.Sqrt(rand.Float64()*100) * 10))
	if rpValue == 0 {
		rpValue = 1
	}
	return getTodayFullDate(), rpValue
}

// Jrrp 结构体
type Jrrp struct {
}

// NewJrrp 创建 Jrrp 实例
func NewJrrp() *Jrrp {
	initDB()
	return &Jrrp{}
}

// findJrrp 查找RP数据
func (j *Jrrp) findJrrp(qqid string, tx *sqlx.Tx) (string, int, error) {
	var date string
	var rpValue int

	query := "SELECT date, rp_value FROM jrrp WHERE qqid = ?"
	err := tx.QueryRow(query, qqid).Scan(&date, &rpValue)
	if err != nil {
		if err == sql.ErrNoRows {
			return "", 0, nil
		}
		return "", 0, err
	}
	return date, rpValue, nil
}

// insertJrrp 插入RP数据
func (j *Jrrp) insertJrrp(qqid string, date string, rpValue int, tx *sqlx.Tx) error {
	query := "INSERT OR REPLACE INTO jrrp (qqid, date, rp_value) VALUES (?, ?, ?)"
	_, err := tx.Exec(query, qqid, date, rpValue)
	return err
}

// GetJrrp 获取RP值
func (j *Jrrp) GetJrrp(qqid string) (int, error) {
	tx, err := sqlite3.GetTran()
	if err != nil {
		return 0, err
	}
	defer tx.Rollback()
	today := getTodayFullDate()

	date, rpValue, err := j.findJrrp(qqid, tx)
	if err != nil {
		return 0, err
	}

	if date == "" || date != today {
		newDate, newRpValue := rpValueConstructor()
		err = j.insertJrrp(qqid, newDate, newRpValue, tx)
		if err != nil {
			return 0, err
		}
		if err = tx.Commit(); err != nil {
			return 0, err
		}
		return newRpValue, nil
	}
	if err = tx.Commit(); err != nil {
		return 0, err
	}
	return rpValue, nil
}

// Close 关闭数据库连接
func (j *Jrrp) Close() {
	sqlite3.GetDB().Close()
}
