import {DefaultCrudRepository, Entity, juggler} from "@loopback/repository";
import {TimeStampedEntity} from "..";

export class TimeStampedRepository<T extends TimeStampedEntity, ID, R extends object = {}> extends DefaultCrudRepository<T, ID, R> {
    constructor(entityClass: typeof Entity & { prototype: T }, dataSource: juggler.DataSource) {
        super(entityClass, dataSource);
        (this.modelClass as any).observe('persist', async (ctx: any) => {
            ctx.data.modifiedAt = new Date();
        });

    }

    async aggregate(query: any[]) {
        const collection = (this.dataSource.connector as any).collection(this.entityClass.modelName);
        return await collection.aggregate(deepMapObj(query)).get();
    }
}


const _ = require('lodash')
const ObjectId = require('mongodb').ObjectID;

function deepMapObj(obj: any): any {
    if (_.isArray(obj)) {
        return obj.map(deepMapObj);
    }
    if (_.isObject(obj)) {
        const newObj = {};
        Object.keys(obj).forEach(key => {
            //@ts-ignore
            newObj[key] = deepMapObj(obj[key]);
        });
        return newObj;
    }
    if (_.isString(obj) && obj.startsWith('oid')) {
        try {
            return ObjectId(obj.slice(3));
        } catch (e) {
            return obj.slice(3);
        }
    }
    return obj;
}


