import { Db, MongoClient } from "mongodb";

let logDB:Db;
async function connGameLogDB() {
    console.log('connect gamelog mongodb ......');
    let logDBUrl:string;
    if(G.config.isG123){
        logDBUrl = "mongodb://root:lffu2bD%5eGn2%5eE%2bE7@blacklagoon-mongo-log-primary.pro.g123-cpp.com:3717,blacklagoon-mongo-log-secondary.pro.g123-cpp.com:3717?replicaSet=mgset-351742307";
    }else{
        logDBUrl = "mongodb://root:lyMaple525458@10.0.1.20:27017/heijiao_gamelog?authSource=admin";
    }
    let client = await MongoClient.connect(logDBUrl,{
        maxPoolSize:10,
        maxIdleTimeMS: 5*60*1000
    });
    logDB = client.db(`gameLog${G.config.serverId}`);
    return logDB;
}

/**
 * 增加游戏日志
 * @param uid 玩家uid
 * @param type 日志类型
 * @param req 客户端请求数据
 * @param data 日志内容
 */

export async function addGameLog(uid:string, type:string, req:any, data:any){
    try{
        if(!logDB){
            await connGameLogDB();
        }
        let log = {
            uid,
            type,
            req,
            data
        }
        //事件时间
        log['cTime'] = Math.floor(Date.now()/1000);

        logDB.collection('gameLog').insertOne(log);
    }catch(e){
        console.error('addGameLog',e);
    }
}

/**
 * 玩家游戏内打点
 * @param uid 玩家uid
 * @param type 日志类型
 * @param data 日志内容
 */

export async function addGameDot(uid:string, type:string, data?:any){
    try{
        if(!logDB){
            await connGameLogDB();
        }
        let log = {
            uid,
            type,
            data
        }
        //事件时间
        log['cTime'] = Math.floor(Date.now()/1000);

        logDB.collection('gameDot').insertOne(log);
    }catch(e){
        console.error('addGameLog',e);
    }
}