

export class ActionLog {
    static async initDayLog(uid: string) {
        G.mongodb.cActionLog('day').updateOne({ uid: uid, type: 'day' }, { $set: { log: {} } }, { upsert: true });
    }
    static async addDayLog(uid: string, ...args: { key: string, val: number; }[]) {
        const addObj = G.mongodb.createTreeObj(...args.map(a => { return { key: 'log', k: a.key, val: a.val }; }));
        G.mongodb.cActionLog('day').updateOne({ uid: uid, type: 'day' }, { $inc: addObj });
    }
    static async getDayLog(uid: string, key: string): Promise<number>;
    static async getDayLog(uid: string, ...keys: string[]): Promise<k_v<number>>;
    static async getDayLog(uid: string, keyArr: string[]): Promise<k_v<number>>;
    static async getDayLog(uid: string) {
        let log = (await G.mongodb.cActionLog('day').findOne({ uid: uid, type: 'day' }))?.log || {};
        if (arguments.length == 2) {
            if (typeof arguments[1] == 'string') return log[arguments[1]] || 0;
            else return Object.fromEntries(arguments[1].map(key => [key, log[key] || 0]));
        }
        return Object.fromEntries(Array.from(arguments).slice(1).map(key => [key, log[key] || 0]));
    }

    static async addRetainLog(uid: string, ...args: { key: string, val: number; }[]) {
        const addObj = G.mongodb.createTreeObj(...args.map(a => { return { key: 'log', k: a.key, val: a.val }; }));
        G.mongodb.cActionLog('retain').updateOne({ uid: uid, type: 'retain' }, { $inc: addObj }, { upsert: true });
    };
    static async getRetainLog(uid: string, key: string): Promise<number>;
    static async getRetainLog(uid: string, ...keys: string[]): Promise<k_v<number>>;
    static async getRetainLog(uid: string, keyArr: string[]): Promise<k_v<number>>;
    static async getRetainLog(uid: string) {
        let log = (await G.mongodb.cActionLog('retain').findOne({ uid: uid, type: 'retain' }))?.log || {};
        if (arguments.length == 2) {
            if (typeof arguments[1] == 'string') return log[arguments[1]] || 0;
            else return Object.fromEntries(arguments[1].map(key => [key, log[key] || 0]));
        }
        return Object.fromEntries(Array.from(arguments).slice(1).map(key => [key, log[key] || 0]));
    }
    static async getLogByTaskType(uid: string, ...tasks: { taskId: string, taskType?: string; }[]) {
        let taskArr = tasks.map(task => { return { ...task, taskType: task.taskType || 'day' }; });
        return taskArr[0].taskType == 'day' ? await this.getDayLog(uid, ...taskArr.map(task => task.taskId)) : await this.getRetainLog(uid, ...taskArr.map(task => task.taskId));
    }
}