package com.example.demo.module.rank;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.GlobalRoot;
import com.example.demo.table.RoomGameRecord;
import pers.jc.sql.SQL;
import pers.jc.util.JCCache;

import java.sql.Timestamp;
import java.util.List;

/**
 * Socket服务-排行
 */
public class RankService {
    public static RankService ins = new RankService();

    public void setRoomNeedCalculatePKScore(String roomKey) {
        JCCache.ins().put(
            "RoomNeedCalculatePKScore_" + roomKey, true,
            System.currentTimeMillis() + 60 * 60 * 1000);
    }

    public boolean isRoomNeedCalculatePKScore(String roomKey) {
        Boolean res = JCCache.ins().get("RoomNeedCalculatePKScore_" + roomKey, Boolean.class);
        if (res == null) return false;
        return res;
    }

    public int getDefaultPkScore() {
        return 1500;
    }

    public Integer getGameScore(int gameType, int userID) {
        SQL sql = new SQL(){{
            SELECT("score");
            FROM("game" + gameType + "_score");
            WHERE("userID=" + PARAM(userID));
        }};
        List<JSONObject> list = GlobalRoot.db.select(sql);
        if (list.size() > 0) {
            return list.get(0).getInteger("score");
        }
        return getDefaultPkScore();
    }

    public void updateGameScore(int gameType, int userID, int score) {
        SQL sql = new SQL(){{
            INSERT_INTO("game" + gameType + "_score");
            VALUES("userID", PARAM(userID));
            VALUES("score", PARAM(score));
            VALUES("update_time", PARAM(new Timestamp(System.currentTimeMillis())));
//            ON_DUPLICATE_KEY_UPDATE("score = score + " + PARAM(score));
            ON_DUPLICATE_KEY_UPDATE("score = " + PARAM(score));
        }};
        GlobalRoot.db.insert(sql);
    }

    public boolean insertRoomGameRecord(
            String roomKey, int gameType, int p1ID, int p2ID, int gameResult
    ) {
        RoomGameRecord roomGameRecord = new RoomGameRecord(roomKey, gameType, p1ID, p2ID, gameResult);
        int insertRes = GlobalRoot.db.insertIgnore(roomGameRecord);
        return insertRes > 0;
    }
}
