import { Db, MongoClient } from "mongodb";
import { Logger } from "tsrpc";

export let logDB:Db;
export let errorLogDB:Db;

/**
 * 是否是G123的测试服
 */
function isG123stg(){
    return G.config.mongodbUrl.indexOf('.stg.')!=-1;
}

export 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}`);
    errorLogDB = client.db(`nodeJsErrorLog`);

    return logDB;
}

export let mylogger: Logger = {
    debug(...args: any[]){
        console.debug(...args);
    },
    log(...args: any[]){
        console.log(...args);
    },
    warn(...args: any[]){
        console.warn(...args);
    },
    error(...args: any[]){
        addErrorLog( args );
        console.error(...args);
    }
}

process.on('uncaughtException',function(err:Error){
    addErrorLog( (err?.stack || err)?.toString() );
})

process.on('unhandledRejection', function (err:Error, promise) {
    addErrorLog( (err?.stack || err)?.toString() );
})

async function addErrorLog(errData:any){
    try{
        //g123测试版连接不上db，不抓取
        if(!errData)return;
        if(isG123stg())return;
        let log = {
            serverId : G.config.serverId,
            pid : process.pid,
            cTime : Math.floor(Date.now()/1000),
            error: errData
        }
        if(!errorLogDB){
            await connGameLogDB();
        }
        errorLogDB.collection('nodeJsErrorLog').insertOne(log);
    }catch(e){
        console.error('addErrorLog',e);
    }
}

export async function addWatchDogLog(data:object[]){
    try{
        //g123测试版连接不上db，不抓取
        if(!data)return;
        if(isG123stg())return;
        let log = {
            serverId : G.config.serverId,
            pid : process.pid,
            cTime : Math.floor(Date.now()/1000)
        }
        data.map(item=>{
            Object.assign(item,log)
        })
        if(!errorLogDB){
            await connGameLogDB();
        }
        errorLogDB.collection('nodeJsErrorLog').insertMany(data);
    }catch(e){
        console.error('addWatchDogLog',e);
    }
}

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

export async function addGameLog(uid:string, type:string, req:any, data:any){
    try{
        //g123测试版连接不上db，不抓取
        if(isG123stg())return;

        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);
    }
}