"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype);
    return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getReportLookupSchemas = getReportLookupSchemas;
exports.buildTree = buildTree;
exports.getLeafValueTypes = getLeafValueTypes;
exports.getLeafFormatTypes = getLeafFormatTypes;
exports.mongoCommand = mongoCommand;
var resolveio_server_app_1 = require("../resolveio-server-app");
var common_1 = require("./common");
function assertLookupCollection(collectionName, referringField) {
    var collectionModel = resolveio_server_app_1.ResolveIOServer.getMongoManager().collection(collectionName);
    if (!collectionModel) {
        var context = referringField ? " referenced by '".concat(referringField, "'") : '';
        throw new Error("Report Builder: collection '".concat(collectionName, "'").concat(context, " is not registered."));
    }
    if (!collectionModel.useRB || !collectionModel.rbSchema) {
        var context = referringField ? " referenced by '".concat(referringField, "'") : '';
        throw new Error("Report Builder: collection '".concat(collectionName, "'").concat(context, " is not configured for Report Builder."));
    }
    return collectionModel;
}
function getReportLookupSchemas(collection_root) {
    var lookupTrees = [];
    var processedCollections = new Set();
    var pendingCollections = [{ name: collection_root, isRoot: true }];
    var _loop_1 = function () {
        var current = pendingCollections.shift();
        if (!current) {
            return "continue";
        }
        if (processedCollections.has(current.name)) {
            return "continue";
        }
        var collectionModel = assertLookupCollection(current.name, current.referringField);
        var schemaObj = collectionModel.rbSchema;
        lookupTrees.push({ collection_name: current.name, tree: schemaObj, is_root: current.isRoot });
        processedCollections.add(current.name);
        Object.keys(schemaObj).forEach(function (field) {
            if (schemaObj[field].lookup_collection && !processedCollections.has(schemaObj[field].lookup_collection)) {
                pendingCollections.push({
                    name: schemaObj[field].lookup_collection,
                    isRoot: false,
                    referringField: "".concat(current.name, ".").concat(field)
                });
            }
        });
    };
    while (pendingCollections.length) {
        _loop_1();
    }
    return lookupTrees;
}
function buildTree(current_root, schemaTree, lookup) {
    var res = [];
    Object.keys(schemaTree).filter(function (a) { return a !== '__v'; }).forEach(function (key) {
        // Object.keys(schemaTree).filter(a => a !== '__v').forEach(key => {
        if (!lookup || (lookup && !schemaTree[key].lookup_collection)) {
            var treeItemSplit = key.split('.');
            // debugger;
            if (treeItemSplit.length === 1) {
                if (schemaTree[key].rbType === 'String' || schemaTree[key].rbType === 'Number' || schemaTree[key].rbType === 'Boolean' || schemaTree[key].rbType === 'Date') {
                    res.push({
                        collection_name: current_root,
                        columnName: (0, common_1.toTitleCase)(key.replace(/\_/g, ' ')),
                        fieldName: key,
                        fieldType: schemaTree[key].rbType,
                        fieldTypeName: schemaTree[key].rbType === 'String' ? 'Text' : (schemaTree[key].rbType === 'Boolean' ? 'T/F' : schemaTree[key].rbType),
                        distinctFieldValues: [],
                        fieldPath: lookup ? lookup.lookup_as + '.$.' + key : key,
                        fieldPathName: lookup ? ((0, common_1.toTitleCase)(lookup.lookup_as.replace(/\.\$\./g, ' (List) -> ').replace(/\./g, ' (Group) -> '))) + ' (List) -> ' + ((0, common_1.toTitleCase)(key.replace(/\.\$\./g, ' (List) -> ').replace(/\./g, ' (Group) -> '))) : (0, common_1.toTitleCase)(key.replace(/\.\$\./g, ' (List) -> ').replace(/\./g, ' (Group) -> ')),
                        lookup_collection: lookup ? lookup.lookup_collection : (schemaTree[key].lookup_collection ? schemaTree[key].lookup_collection : ''),
                        lookup_local_key: lookup ? lookup.lookup_local_key : (schemaTree[key].lookup_collection ? schemaTree[key].local_key : ''),
                        lookup_foreign_key: lookup ? lookup.lookup_foreign_key : (schemaTree[key].lookup_collection ? schemaTree[key].lookup_key : ''),
                        lookup_as: lookup ? lookup.lookup_as : (schemaTree[key].lookup_collection ? schemaTree[key].lookup_as : ''),
                        text: (0, common_1.toTitleCase)(key.replace(/\_/g, ' ')),
                        value: key,
                        isLeaf: true,
                        isActive: false,
                        isSelected: false,
                        depth: 0,
                        leafValueType: '',
                        leafValueTypes: getLeafValueTypes(schemaTree[key], key),
                        leafFormatType: '',
                        leafFormatTypes: getLeafFormatTypes(schemaTree[key], key)
                    });
                }
                else {
                    res.push({
                        collection_name: current_root,
                        columnName: (0, common_1.toTitleCase)(key.replace(/\_/g, ' ')),
                        fieldName: key,
                        fieldType: schemaTree[key].lookup_collection ? 'Lookup' : schemaTree[key].rbType,
                        fieldTypeName: schemaTree[key].lookup_collection ? 'Lookup' : (schemaTree[key].rbType === 'Array' ? 'List' : 'Group'),
                        distinctFieldValues: [],
                        fieldPath: lookup ? lookup.lookup_as + '.$.' + key : key,
                        fieldPathName: lookup ? ((0, common_1.toTitleCase)(lookup.lookup_as.replace(/\.\$\./g, ' (List) -> ').replace(/\./g, ' (Group) -> '))) + ' (List) -> ' + ((0, common_1.toTitleCase)(key.replace(/\.\$\./g, ' (List) -> ').replace(/\./g, ' (Group) -> '))) : (0, common_1.toTitleCase)(key.replace(/\.\$\./g, ' (List) -> ').replace(/\./g, ' (Group) -> ')),
                        lookup_collection: lookup ? lookup.lookup_collection : (schemaTree[key].lookup_collection ? schemaTree[key].lookup_collection : ''),
                        lookup_local_key: lookup ? lookup.lookup_local_key : (schemaTree[key].lookup_collection ? schemaTree[key].local_key : ''),
                        lookup_foreign_key: lookup ? lookup.lookup_foreign_key : (schemaTree[key].lookup_collection ? schemaTree[key].lookup_key : ''),
                        lookup_as: lookup ? lookup.lookup_as : (schemaTree[key].lookup_collection ? schemaTree[key].lookup_as : ''),
                        text: (0, common_1.toTitleCase)(key.replace(/\_/g, ' ')),
                        value: key,
                        isLeaf: false,
                        isActive: false,
                        isSelected: false,
                        depth: 0,
                        leafValueType: '',
                        leafFormatType: '',
                        children: []
                    });
                }
                res = res.sort(function (a, b) { return a.fieldName.localeCompare(b.fieldName); });
            }
            else {
                var child_1 = null;
                treeItemSplit.forEach(function (layer, index) {
                    if (!child_1) {
                        child_1 = res.find(function (a) { return a.fieldName === layer; });
                    }
                    else {
                        if (child_1.children.find(function (a) { return a.fieldName === layer; })) {
                            child_1 = child_1.children.find(function (a) { return a.fieldName === layer; });
                        }
                        else {
                            if (schemaTree[key].rbType === 'String' || schemaTree[key].rbType === 'Number' || schemaTree[key].rbType === 'Boolean' || schemaTree[key].rbType === 'Date') {
                                child_1.children.push({
                                    collection_name: current_root,
                                    columnName: (0, common_1.toTitleCase)(key.replace(/\_/g, ' ')),
                                    fieldName: layer,
                                    fieldType: schemaTree[key].rbType,
                                    fieldTypeName: schemaTree[key].rbType === 'String' ? 'Text' : (schemaTree[key].rbType === 'Boolean' ? 'T/F' : schemaTree[key].rbType),
                                    distinctFieldValues: [],
                                    fieldPath: lookup ? lookup.lookup_as + '.$.' + key : key,
                                    fieldPathName: lookup ? ((0, common_1.toTitleCase)(lookup.lookup_as.replace(/\.\$\./g, ' (List) -> ').replace(/\./g, ' (Group) -> '))) + ' (List) -> ' + ((0, common_1.toTitleCase)(key.replace(/\.\$\./g, ' (List) -> ').replace(/\./g, ' (Group) -> '))) : (0, common_1.toTitleCase)(key.replace(/\.\$\./g, ' (List) -> ').replace(/\./g, ' (Group) -> ')),
                                    lookup_collection: lookup ? lookup.lookup_collection : (schemaTree[key].lookup_collection ? schemaTree[key].lookup_collection : ''),
                                    lookup_local_key: lookup ? lookup.lookup_local_key : (schemaTree[key].lookup_collection ? schemaTree[key].local_key : ''),
                                    lookup_foreign_key: lookup ? lookup.lookup_foreign_key : (schemaTree[key].lookup_collection ? schemaTree[key].lookup_key : ''),
                                    lookup_as: lookup ? lookup.lookup_as : (schemaTree[key].lookup_collection ? schemaTree[key].lookup_as : ''),
                                    text: (0, common_1.toTitleCase)(layer.replace(/\_/g, ' ')),
                                    value: layer,
                                    isLeaf: true,
                                    isActive: false,
                                    isSelected: false,
                                    depth: index,
                                    leafValueType: '',
                                    leafValueTypes: getLeafValueTypes(schemaTree[key], key),
                                    leafFormatType: '',
                                    leafFormatTypes: getLeafFormatTypes(schemaTree[key], key)
                                });
                            }
                            else {
                                child_1.children.push({
                                    collection_name: current_root,
                                    columnName: (0, common_1.toTitleCase)(key.replace(/\_/g, ' ')),
                                    fieldName: layer,
                                    fieldType: schemaTree[key].lookup_collection ? 'Lookup' : schemaTree[key].rbType,
                                    fieldTypeName: schemaTree[key].lookup_collection ? 'Lookup' : (schemaTree[key].rbType === 'Array' ? 'List' : 'Group'),
                                    distinctFieldValues: [],
                                    fieldPath: lookup ? lookup.lookup_as + '.$.' + key : key,
                                    fieldPathName: lookup ? ((0, common_1.toTitleCase)(lookup.lookup_as.replace(/\.\$\./g, ' (List) -> ').replace(/\./g, ' (Group) -> '))) + ' (List) -> ' + ((0, common_1.toTitleCase)(key.replace(/\.\$\./g, ' (List) -> ').replace(/\./g, ' (Group) -> '))) : (0, common_1.toTitleCase)(key.replace(/\.\$\./g, ' (List) -> ').replace(/\./g, ' (Group) -> ')),
                                    lookup_collection: lookup ? lookup.lookup_collection : (schemaTree[key].lookup_collection ? schemaTree[key].lookup_collection : ''),
                                    lookup_local_key: lookup ? lookup.lookup_local_key : (schemaTree[key].lookup_collection ? schemaTree[key].local_key : ''),
                                    lookup_foreign_key: lookup ? lookup.lookup_foreign_key : (schemaTree[key].lookup_collection ? schemaTree[key].lookup_key : ''),
                                    lookup_as: lookup ? lookup.lookup_as : (schemaTree[key].lookup_collection ? schemaTree[key].lookup_as : ''),
                                    text: (0, common_1.toTitleCase)(layer.replace(/\_/g, ' ')),
                                    value: layer,
                                    isLeaf: false,
                                    isActive: false,
                                    isSelected: false,
                                    depth: index,
                                    leafValueType: '',
                                    leafFormatType: '',
                                    children: []
                                });
                            }
                            child_1.children = child_1.children.sort(function (a, b) { return a.fieldName.localeCompare(b.fieldName); });
                        }
                    }
                });
            }
        }
    });
    return res;
}
// eslint-disable-next-line no-unused-vars
function getLeafValueTypes(schemaTree, fieldPath) {
    var leafTypes = [];
    if (schemaTree.rbType === 'String') {
        leafTypes = [
            {
                text: 'As Value',
                value: 'Value'
            },
            {
                text: 'Unique',
                value: 'Unique'
            },
            {
                text: 'As Count',
                value: 'Count'
            },
            {
                text: 'First',
                value: 'First'
            },
            {
                text: 'Last',
                value: 'Last'
            }
        ];
    }
    else if (schemaTree.rbType === 'Number') {
        leafTypes = [
            {
                text: 'As Value',
                value: 'Value'
            },
            {
                text: 'Unique',
                value: 'Unique'
            },
            {
                text: 'As Average',
                value: 'Average'
            },
            {
                text: 'As Count',
                value: 'Count'
            },
            {
                text: 'As Sum',
                value: 'Sum'
            },
            {
                text: 'Minimum',
                value: 'Minimum'
            },
            {
                text: 'Maximum',
                value: 'Maximum'
            },
            {
                text: 'First',
                value: 'First'
            },
            {
                text: 'Last',
                value: 'Last'
            }
        ];
    }
    else if (schemaTree.rbType === 'Boolean') {
        leafTypes = [
            {
                text: 'As Value',
                value: 'Value'
            },
            {
                text: 'Unique',
                value: 'Unique'
            },
            {
                text: 'As Count',
                value: 'Count'
            },
            {
                text: 'First',
                value: 'First'
            },
            {
                text: 'Last',
                value: 'Last'
            }
        ];
    }
    else if (schemaTree.rbType === 'Date') {
        leafTypes = [
            {
                text: 'As Value',
                value: 'Value'
            },
            {
                text: 'Unique',
                value: 'Unique'
            },
            {
                text: 'As Count',
                value: 'Count'
            },
            {
                text: 'Minimum',
                value: 'Minimum'
            },
            {
                text: 'Maximum',
                value: 'Maximum'
            },
            {
                text: 'First',
                value: 'First'
            },
            {
                text: 'Last',
                value: 'Last'
            }
        ];
    }
    return leafTypes;
}
// eslint-disable-next-line no-unused-vars
function getLeafFormatTypes(schemaTree, fieldPath) {
    var leafTypes = [];
    if (schemaTree.rbType === 'String') {
        leafTypes = [
            {
                text: 'As Text',
                value: 'String'
            },
            {
                text: 'As Number',
                value: 'Number'
            }
        ];
    }
    else if (schemaTree.rbType === 'Number') {
        leafTypes = [
            {
                text: 'As Number',
                value: 'Number'
            },
            {
                text: 'As Currency',
                value: 'Currency'
            },
            {
                text: 'As Text',
                value: 'String'
            }
        ];
    }
    else if (schemaTree.rbType === 'Boolean') {
        leafTypes = [
            {
                text: 'As Number',
                value: 'Number'
            },
            {
                text: 'As Boolean (True/False)',
                value: 'Boolean'
            },
            {
                text: 'As Text (Yes/No)',
                value: 'String'
            },
            {
                text: 'As Number (1/0)',
                value: 'Boolean_Number'
            }
        ];
    }
    else if (schemaTree.rbType === 'Date') {
        leafTypes = [
            {
                text: 'As Number',
                value: 'Number'
            },
            {
                text: 'As Date (Short Format)',
                value: 'Date'
            },
            {
                text: 'As Time (Short Format)',
                value: 'Time'
            },
            {
                text: 'As Date/Time (Short Format)',
                value: 'DateTime'
            },
            {
                text: 'As Date (Long Format)',
                value: 'Date_long'
            },
            {
                text: 'As Date/Time (Long Format)',
                value: 'DateTime_long'
            },
            {
                text: 'As Timestamp (MS since 1970)',
                value: 'Timestamp'
            }
        ];
    }
    return leafTypes;
}
function mongoCommand(commandstr, collection, field) {
    return __awaiter(this, void 0, void 0, function () {
        var tmpObj, obj, obj, _a;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _b.trys.push([0, 6, , 7]);
                    if (!(commandstr === 'count')) return [3 /*break*/, 2];
                    obj = {
                        count: collection,
                        query: {}
                    };
                    obj.query[field] = { $ne: null };
                    return [4 /*yield*/, resolveio_server_app_1.ResolveIOServer.getMainDB().command(obj)];
                case 1:
                    tmpObj = _b.sent();
                    return [3 /*break*/, 5];
                case 2:
                    if (!(commandstr === 'distinct')) return [3 /*break*/, 4];
                    obj = {
                        distinct: collection,
                        query: {},
                        key: field,
                    };
                    return [4 /*yield*/, resolveio_server_app_1.ResolveIOServer.getMainDB().command(obj)];
                case 3:
                    tmpObj = _b.sent();
                    return [3 /*break*/, 5];
                case 4:
                    if (commandstr === 'listIndexes') {
                        // tmpObj = await this.mainDb.db[collection].getIndexes();
                        // let obj = { 'listIndexes': collection };
                        // tmpObj = await this.mainDb.db.getIndexes(obj);
                    }
                    _b.label = 5;
                case 5: return [3 /*break*/, 7];
                case 6:
                    _a = _b.sent();
                    // console.log('----------- mongoCommand err: ', err);
                    return [2 /*return*/, -1];
                case 7:
                    if (tmpObj) {
                        return [2 /*return*/, tmpObj.values];
                    }
                    return [2 /*return*/];
            }
        });
    });
}

//# sourceMappingURL=schema-report-builder.js.map
