package com.example.demo.module.user;

import com.alibaba.fastjson.JSONObject;
import com.example.demo.common.GlobalRoot;
import com.example.demo.table.UserGameRecord;
import pers.jc.network.SocketComponent;
import pers.jc.network.SocketMethod;
import pers.jc.network.SocketResponse;
import pers.jc.sql.SQL;

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

/**
 * Socket组件-用户游戏情况分析
 */
@SocketComponent("UserGameAnalyseComp")
public class UserGameAnalyseComp {

    @SocketMethod(async = true)
    public void uploadUserGameRecord(Player player, int gameType, long startTime, int duration) {
        int final_duration = duration > 1 ? duration : 1;
        GlobalRoot.db.insert(new SQL(){{
            INSERT_INTO(UserGameRecord.class);
            VALUES("userID", PARAM(player.userID));
            VALUES("dateTime", PARAM(new Timestamp(startTime)));
            VALUES("gameType", PARAM(gameType));
            VALUES("duration", PARAM(final_duration));
            ON_DUPLICATE_KEY_UPDATE("duration = if(duration<" + final_duration + "," + final_duration + ",duration)");
        }});
    }

    @SocketMethod(async = true)
    public void getUserGamePlayTime(Player player, SocketResponse socketResponse) {
        List<JSONObject> list = GlobalRoot.db.select(new SQL(){{
            FROM("user_game_record");
            SELECT("gameType");
            SELECT("sum(duration) as totalDuration");
            WHERE("userID = " + PARAM(player.userID));
            GROUP_BY("gameType");
        }});
        socketResponse.send(list);
    }
}
