"use strict";
/**
 * campus controller
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.omitFieldsRecursively = void 0;
const strapi_1 = require("@strapi/strapi");
exports.default = strapi_1.factories.createCoreController("api::campus.campus", ({ strapi }) => ({
    async findOne(ctx) {
        const result = await super.find(ctx);
        return result;
    },
    async find(ctx) {
        if (typeof ctx.query.populate == "undefined") {
            ctx.query = { ...ctx.query, populate: ["coordinates", "network"] };
            const result = await super.find(ctx);
            result.data.forEach((it) => {
                it.attributes.coordinates = {
                    ...it.attributes.coordinates,
                    color: it.attributes.network.data.attributes.chartBg,
                    // color: faker.color.rgb(),
                };
                console.log(it.attributes.network);
            });
            return result;
        }
        if (ctx.query.populate == "*") {
            const result = await super.find(ctx);
            result.data.forEach((it) => {
                it.attributes.coordinates = {
                    ...it.attributes.coordinates,
                    color: it.attributes.network.data.attributes.chartBg,
                    // color: faker.color.rgb(),
                };
            });
            return result;
        }
        if (ctx.query.populate == "coordinates") {
            ctx.query = { ...ctx.query, populate: ["coordinates", "network"] };
            const result = await super.find(ctx);
            result.data.forEach((it) => {
                it.attributes.coordinates = {
                    ...it.attributes.coordinates,
                    color: it.attributes.network.data.attributes.chartBg,
                    // color: faker.color.rgb(),
                };
            });
            return result;
        }
        const result = await super.find(ctx);
        return result;
    },
    async data(ctx) {
        let query = ctx.query;
        let entry = {};
        if (query.networkid && query.count == "all") {
            let campuses = await strapi.db.query("api::campus.campus").findMany({
                where: {
                    network: {
                        id: {
                            $eq: query.networkid,
                        },
                    },
                },
                populate: true,
            });
            entry["campuses"] = {};
            // entry["campuses"]["items"] = campuses;
            entry["campuses"]["number"] = campuses.length;
            let dgs = [];
            campuses.forEach((it, idx) => {
                let dg = strapi.db
                    .query("api::discipleship-group.discipleship-group")
                    .findMany({
                    populate: true,
                    where: {
                        campus: {
                            id: {
                                $eq: it.id,
                            },
                        },
                    },
                });
                dgs.push(dg);
            });
            let unflattened = await Promise.all(dgs);
            entry["dgs"] = {};
            // entry["dgs"]["items"] = unflattened;
            entry["dgs"]["number"] = unflattened.flat().length;
            let full = new Map();
            unflattened.forEach((campusDgs, idx) => {
                let membersPromise = new Map();
                // console.log("cdgs", campusDgs);
                campusDgs.forEach((dg, index) => {
                    let members = strapi.db.query("api::member.member").findMany({
                        where: {
                            discipleshipGroup: {
                                id: {
                                    $eq: dg.id,
                                },
                            },
                        },
                        populate: true,
                    });
                    membersPromise.set(dg.id, members);
                });
                full.set(campuses[idx].id, membersPromise);
            });
            let membersCount = 0;
            for (let [key, values] of full) {
                console.log("values: " + values);
                for (let [key, item] of values) {
                    let results = await item;
                    membersCount += results.length;
                    values.set(key, results);
                }
            }
            let fullObj = Object.fromEntries(full);
            for (const mappp in fullObj) {
                fullObj[mappp] = Object.fromEntries(fullObj[mappp]);
            }
            console.log(fullObj);
            fullObj.number = membersCount;
            entry["members"] = {
                number: membersCount,
            };
        }
        else if (query.networkid) {
            //  ///////////////////////////////////////////////////////////////////////////////////////////////////////
            let campuses = await strapi.db.query("api::campus.campus").findMany({
                where: {
                    network: {
                        id: {
                            $eq: query.networkid,
                        },
                    },
                },
                populate: true,
            });
            // entry["campuses"] = {};
            // entry["campuses"]["items"] = campuses;
            entry["campuses"] = campuses.length;
            let dgs = [];
            campuses.forEach((it, idx) => {
                let dg = strapi.db
                    .query("api::discipleship-group.discipleship-group")
                    .findMany({
                    populate: true,
                    where: {
                        campus: {
                            id: {
                                $eq: it.id,
                            },
                        },
                    },
                });
                dgs.push(dg);
            });
            let unflattened = await Promise.all(dgs);
            // entry["dgs"] = {};
            // entry["dgs"]["items"] = unflattened;
            entry["discipleshipGroup"] = unflattened.flat().length;
            let full = new Map();
            unflattened.forEach((campusDgs, idx) => {
                let membersPromise = new Map();
                campusDgs.forEach((dg, index) => {
                    let members = strapi.db.query("api::member.member").count({
                        where: {
                            discipleshipGroup: {
                                id: {
                                    $eq: dg.id,
                                },
                            },
                        },
                        populate: true,
                    });
                    membersPromise.set(dg.id, members);
                });
                full.set(campuses[idx].id, membersPromise);
            });
            let membersCount = 0;
            for (let [key, values] of full) {
                console.log("values: " + values);
                for (let [key, item] of values) {
                    let results = await item;
                    membersCount += results;
                    values.set(key, results);
                }
            }
            let fullObj = Object.fromEntries(full);
            for (const mappp in fullObj) {
                fullObj[mappp] = Object.fromEntries(fullObj[mappp]);
            }
            entry["members"] = membersCount;
        }
        entry = omitFieldsRecursively(entry);
        try {
            ctx.body = entry;
        }
        catch (err) {
            ctx.body = err;
        }
    },
    async summary(ctx) { },
}));
function convertMapToObject(item) { }
function omitFieldsRecursively(obj, fieldsToOmit = [
    "createdAt",
    "createdBy",
    "updatedAt",
    "updatedBy",
    "publishedAt",
    "_softDeletedAt",
    "_softDeletedById",
    "_softDeletedByType",
]) {
    if (typeof obj !== "object" || obj === null) {
        return obj; // Return as-is if the input is not an object
    }
    if (Array.isArray(obj)) {
        return obj.map((item) => omitFieldsRecursively(item, fieldsToOmit));
    }
    const newObj = { ...obj }; // Create a shallow copy of the original object
    for (const field of fieldsToOmit) {
        delete newObj[field]; // Remove the specified field from the copied object
    }
    for (const key in newObj) {
        newObj[key] = omitFieldsRecursively(newObj[key], fieldsToOmit); // Recursively process nested objects
    }
    return newObj; // Return the modified object
}
exports.omitFieldsRecursively = omitFieldsRecursively;
