var __assign = (this && this.__assign) || function () {
    __assign = Object.assign || function(t) {
        for (var s, i = 1, n = arguments.length; i < n; i++) {
            s = arguments[i];
            for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
                t[p] = s[p];
        }
        return t;
    };
    return __assign.apply(this, arguments);
};
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;
    return g = { next: verb(0), "throw": verb(1), "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 (_) 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 };
    }
};
var errors = require('../utils/errors.util').errors;
function TreeController() {
}
/**
 * extract node(s) from object
 * @param tree {object} - try to append a node
 * @param data {object} - data target to extract nodes
 * @param nodeKey {string} - node key from main data
 * @param nodePath {string | null} - full path of that node
 * @param opts - options {
 *     nodeHandler: ({name, path, node})=>{}, // called each time node found;
       nodeIdHandler: ()=>{return null;} // called when want to process secondary data id;
 * }
 * @returns {Promise<object>} - tree after append a node
 */
TreeController.prototype.node = function (tree, data, nodeKey, nodePath, opts) {
    var _this = this;
    if (nodePath === void 0) { nodePath = null; }
    if (opts === void 0) { opts = {
        nodeHandler: function (_a) {
            var name = _a.name, path = _a.path, node = _a.node;
            return __awaiter(_this, void 0, void 0, function () {
                return __generator(this, function (_b) {
                    return [2 /*return*/];
                });
            });
        },
        nodeIdHandler: function () { return __awaiter(_this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, null];
            });
        }); }
    }; }
    return __awaiter(this, void 0, void 0, function () {
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    if (typeof tree === 'boolean' || !tree) {
                        throw errors.TREE_NOT_FOUND;
                    }
                    if (typeof data === 'boolean' || !data) {
                        throw errors.DATA_NOT_FOUND;
                    }
                    if (typeof nodeKey === 'boolean' || !nodeKey) {
                        throw errors.NODE_KEY_NOT_FOUND;
                    }
                    if (data.hasOwnProperty('_id') === false) {
                        throw errors.ID_NOT_FOUND;
                    }
                    if (typeof nodePath === 'boolean' || !nodePath) {
                        nodePath = nodeKey;
                    }
                    if (!opts || typeof opts === "boolean") {
                        opts = {};
                    }
                    if (typeof opts.nodeHandler === 'boolean' || !opts.nodeHandler) {
                        opts.nodeHandler = function (_a) {
                            var node = _a.node, name = _a.name, tree = _a.tree, path = _a.path;
                            return __awaiter(this, void 0, void 0, function () {
                                return __generator(this, function (_b) {
                                    return [2 /*return*/];
                                });
                            });
                        };
                    }
                    if (!tree.hasOwnProperty(nodeKey)) {
                        tree[nodeKey] = {};
                    }
                    if (!(data.hasOwnProperty(nodeKey) &&
                        typeof data[nodeKey] === "object" &&
                        !Array.isArray(data[nodeKey]) &&
                        JSON.stringify(data[nodeKey]).startsWith('{') &&
                        data[nodeKey] !== null &&
                        data[nodeKey] !== undefined)) return [3 /*break*/, 2];
                    return [4 /*yield*/, handleMap(tree, data, nodeKey, nodePath, opts)];
                case 1:
                    tree = _a.sent();
                    return [3 /*break*/, 6];
                case 2:
                    if (!(data.hasOwnProperty(nodeKey) &&
                        Array.isArray(data[nodeKey]) &&
                        data[nodeKey] !== null &&
                        data[nodeKey] !== undefined)) return [3 /*break*/, 4];
                    return [4 /*yield*/, handleArray(tree, data, nodeKey, nodePath, opts)];
                case 3:
                    tree = _a.sent();
                    return [3 /*break*/, 6];
                case 4: return [4 /*yield*/, processANode(tree, data, nodeKey, nodePath, opts)];
                case 5:
                    tree = _a.sent();
                    _a.label = 6;
                case 6:
                    delete tree._id;
                    return [2 /*return*/, tree];
            }
        });
    });
};
/**
 *
 * @param data {object | Array<object>} - data to covert to tree
 * @param domain {string} - data namespace to use
 * @param opts - options {
 *     nodeHandler: ({name, path, node})=>{}, // called each time node found;
       nodeIdHandler: ()=>{return null;} // called when want to process secondary data id;
 * }
 * @returns {Promise<object>} - resolve to tree of nodes for that data
 */
TreeController.prototype.objectToTree = function (data, domain, opts) {
    var _this = this;
    if (opts === void 0) { opts = {
        nodeHandler: function (_a) {
            var name = _a.name, path = _a.path, node = _a.node;
            return __awaiter(_this, void 0, void 0, function () {
                return __generator(this, function (_b) {
                    return [2 /*return*/];
                });
            });
        },
        nodeIdHandler: function () { return __awaiter(_this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, null];
            });
        }); }
    }; }
    return __awaiter(this, void 0, void 0, function () {
        var tree, idNode, processTree, _i, data_1, _data;
        var _this = this;
        return __generator(this, function (_a) {
            switch (_a.label) {
                case 0:
                    tree = {};
                    idNode = {};
                    if (typeof domain === 'boolean' || !domain || domain === '') {
                        throw errors.DOMAIN_NOT_FOUND;
                    }
                    processTree = function (d) { return __awaiter(_this, void 0, void 0, function () {
                        var _i, _a, nodeKey, _b, _c;
                        return __generator(this, function (_d) {
                            switch (_d.label) {
                                case 0:
                                    if (typeof d === 'boolean' || !d) {
                                        throw errors.DATA_NOT_FOUND;
                                    }
                                    _i = 0, _a = Object.keys(d);
                                    _d.label = 1;
                                case 1:
                                    if (!(_i < _a.length)) return [3 /*break*/, 5];
                                    nodeKey = _a[_i];
                                    if (!(nodeKey && typeof nodeKey !== "boolean")) return [3 /*break*/, 3];
                                    return [4 /*yield*/, this.node(tree, d, nodeKey, domain + "/" + nodeKey, opts)];
                                case 2:
                                    tree = _d.sent();
                                    return [3 /*break*/, 4];
                                case 3:
                                    console.log('skip node key is malformed---->', nodeKey);
                                    _d.label = 4;
                                case 4:
                                    _i++;
                                    return [3 /*break*/, 1];
                                case 5:
                                    _b = idNode;
                                    _c = d._id;
                                    return [4 /*yield*/, opts.nodeIdHandler()];
                                case 6:
                                    _b[_c] = _d.sent();
                                    return [4 /*yield*/, opts.nodeHandler({
                                            name: '_id',
                                            node: idNode,
                                            path: domain + "/_id"
                                        })];
                                case 7:
                                    _d.sent();
                                    return [2 /*return*/];
                            }
                        });
                    }); };
                    if (!Array.isArray(data)) return [3 /*break*/, 5];
                    _i = 0, data_1 = data;
                    _a.label = 1;
                case 1:
                    if (!(_i < data_1.length)) return [3 /*break*/, 4];
                    _data = data_1[_i];
                    return [4 /*yield*/, processTree(_data)];
                case 2:
                    _a.sent();
                    _a.label = 3;
                case 3:
                    _i++;
                    return [3 /*break*/, 1];
                case 4: return [3 /*break*/, 7];
                case 5: return [4 /*yield*/, processTree(data)];
                case 6:
                    _a.sent();
                    _a.label = 7;
                case 7:
                    tree._id = idNode;
                    return [2 /*return*/, tree];
            }
        });
    });
};
/**
 *
 * @param domain {string} table/collection/domain where we want to execute query
 * @param query {object | Array<object>} query that we want to execute
 * @returns {Promise<{[key: string]:string} | Array<{[key: string]:string}>>}
 */
TreeController.prototype.query = function (domain, query) {
    return __awaiter(this, void 0, void 0, function () {
        var orQuery, _i, query_1, _query, _a, _b;
        return __generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    if (!Array.isArray(query)) return [3 /*break*/, 5];
                    orQuery = [];
                    _i = 0, query_1 = query;
                    _c.label = 1;
                case 1:
                    if (!(_i < query_1.length)) return [3 /*break*/, 4];
                    _query = query_1[_i];
                    _b = (_a = orQuery).push;
                    return [4 /*yield*/, handleQueryMap({}, _query, [domain])];
                case 2:
                    _b.apply(_a, [_c.sent()]);
                    _c.label = 3;
                case 3:
                    _i++;
                    return [3 /*break*/, 1];
                case 4: return [2 /*return*/, orQuery];
                case 5:
                    if (query && typeof query === "object" && JSON.stringify(query).startsWith('{')) {
                        return [2 /*return*/, handleQueryMap({}, query, [domain])];
                    }
                    throw errors.QUERY_NOT_FOUND;
            }
        });
    });
};
/**
 *
 * @param tree {object}
 * @param data {object}
 * @param nodeKey {string}
 * @param nodePath {string}
 * @param opts - options {
 *     nodeHandler: ({name, path, node})=>{}, // called each time node found;
       nodeIdHandler: ()=>{return null;} // called when want to process secondary data id;
 * }
 * @returns {Promise<object>}
 */
function handleMap(tree, data, nodeKey, nodePath, opts) {
    return __awaiter(this, void 0, void 0, function () {
        var _i, _a, _key, _b, _c;
        return __generator(this, function (_d) {
            switch (_d.label) {
                case 0:
                    _i = 0, _a = Object.keys(data[nodeKey]);
                    _d.label = 1;
                case 1:
                    if (!(_i < _a.length)) return [3 /*break*/, 6];
                    _key = _a[_i];
                    if (!(_key && typeof _key !== "boolean")) return [3 /*break*/, 3];
                    data[nodeKey]._id = data._id;
                    _b = tree;
                    _c = nodeKey;
                    return [4 /*yield*/, TreeController.prototype.node(tree[nodeKey], data[nodeKey], _key, nodePath + "/" + _key, opts)];
                case 2:
                    _b[_c] = _d.sent();
                    return [3 /*break*/, 4];
                case 3:
                    console.log('skip key node is malformed---->', _key === null || _key === void 0 ? void 0 : _key.toString());
                    _d.label = 4;
                case 4:
                    delete data[nodeKey]._id;
                    _d.label = 5;
                case 5:
                    _i++;
                    return [3 /*break*/, 1];
                case 6: return [2 /*return*/, tree];
            }
        });
    });
}
/**
 *
 * @param tree {object}
 * @param data {object}
 * @param pathParts {Array<string>}
 * @returns {Promise<object>}
 */
function handleQueryMap(tree, data, pathParts) {
    return __awaiter(this, void 0, void 0, function () {
        var _i, _a, key;
        return __generator(this, function (_b) {
            switch (_b.label) {
                case 0:
                    _i = 0, _a = Object.keys(data);
                    _b.label = 1;
                case 1:
                    if (!(_i < _a.length)) return [3 /*break*/, 8];
                    key = _a[_i];
                    pathParts.push(key);
                    if (!(typeof data[key] === "object" &&
                        !Array.isArray(data[key]) &&
                        JSON.stringify(data[key]).startsWith('{'))) return [3 /*break*/, 5];
                    if (!(data[key].$fn && typeof data[key].$fn === "string")) return [3 /*break*/, 2];
                    tree[pathParts.join('/')] = {
                        $fn: data[key].$fn
                    };
                    if (data[key].hasOwnProperty('$orderBy')) {
                        tree[pathParts.join('/')] = Object.assign(tree[pathParts.join('/')], {
                            $orderBy: data[key].$orderBy
                        });
                    }
                    if (data[key].hasOwnProperty('$limit')) {
                        tree[pathParts.join('/')] = Object.assign(tree[pathParts.join('/')], {
                            $limit: data[key].$limit
                        });
                    }
                    if (data[key].hasOwnProperty('$skip')) {
                        tree[pathParts.join('/')] = Object.assign(tree[pathParts.join('/')], {
                            $skip: data[key].$skip
                        });
                    }
                    return [3 /*break*/, 4];
                case 2: return [4 /*yield*/, handleQueryMap(tree, data[key], pathParts)];
                case 3:
                    tree = _b.sent();
                    _b.label = 4;
                case 4: return [3 /*break*/, 6];
                case 5:
                    if (Array.isArray(data[key])) {
                        throw errors.INNER_QUERY_DATA_INVALID;
                    }
                    else {
                        tree[pathParts.join('/')] = data[key];
                    }
                    _b.label = 6;
                case 6:
                    pathParts.splice(pathParts.length - 1, 1);
                    _b.label = 7;
                case 7:
                    _i++;
                    return [3 /*break*/, 1];
                case 8: return [2 /*return*/, tree];
            }
        });
    });
}
/**
 *
 * @param tree {object}
 * @param data {object}
 * @param nodeKey {string}
 * @param nodePath {string}
 * @param opts - options {
 *     nodeHandler: ({name, path, node})=>{}, // called each time node found;
       nodeIdHandler: ()=>{return null;} // called when want to process secondary data id;
 * }
 * @returns {Promise<object>}
 */
function handleArray(tree, data, nodeKey, nodePath, opts) {
    return __awaiter(this, void 0, void 0, function () {
        var _i, _a, arrayItem, _data, _b, _c;
        var _d, _e, _f;
        return __generator(this, function (_g) {
            switch (_g.label) {
                case 0:
                    _i = 0, _a = data[nodeKey];
                    _g.label = 1;
                case 1:
                    if (!(_i < _a.length)) return [3 /*break*/, 9];
                    arrayItem = _a[_i];
                    if (!(typeof arrayItem === 'object' && !Array.isArray(arrayItem))) return [3 /*break*/, 3];
                    return [4 /*yield*/, handleMap(tree, (_d = {}, _d[nodeKey] = arrayItem, _d._id = data._id, _d), nodeKey, nodePath, opts)];
                case 2:
                    tree = _g.sent();
                    return [3 /*break*/, 8];
                case 3:
                    if (!Array.isArray(arrayItem)) return [3 /*break*/, 5];
                    return [4 /*yield*/, handleArray(tree, (_e = {}, _e[nodeKey] = arrayItem, _e._id = data._id, _e), nodeKey, nodePath, opts)];
                case 4:
                    tree = _g.sent();
                    return [3 /*break*/, 8];
                case 5:
                    _data = (_f = {}, _f[arrayItem] = arrayItem, _f._id = data._id, _f._list = true, _f);
                    if (!(arrayItem && typeof arrayItem !== "boolean")) return [3 /*break*/, 7];
                    _b = tree;
                    _c = nodeKey;
                    return [4 /*yield*/, TreeController.prototype.node(tree[nodeKey], _data, arrayItem, "" + nodePath, opts)];
                case 6:
                    _b[_c] = _g.sent();
                    return [3 /*break*/, 8];
                case 7:
                    console.log('skip node key in array item is malformed--->', arrayItem);
                    _g.label = 8;
                case 8:
                    _i++;
                    return [3 /*break*/, 1];
                case 9: return [2 /*return*/, tree];
            }
        });
    });
}
/**
 *
 * @param tree {object}
 * @param data {object}
 * @param nodeKey {string}
 * @param nodePath {string}
 * @param opts - options {
 *     nodeHandler: ({name, path, node})=>{}, // called each time node found;
       nodeIdHandler: ()=>{return null;} // called when want to process secondary data id;
 * }
 * @returns {Promise<object>}
 */
function processANode(tree, data, nodeKey, nodePath, opts) {
    return __awaiter(this, void 0, void 0, function () {
        var _a, _b, e_1, _c, _d, e_2;
        var _e;
        return __generator(this, function (_f) {
            switch (_f.label) {
                case 0:
                    if (!opts || typeof opts === "boolean") {
                        opts = {};
                    }
                    if (!opts.nodeIdHandler || typeof opts.nodeHandler !== 'function') {
                        opts.nodeIdHandler = function () {
                            return null;
                        };
                    }
                    if (!(tree.hasOwnProperty(nodeKey) && tree[nodeKey] !== undefined && tree[nodeKey] !== null)) {
                        tree[nodeKey] = {};
                    }
                    if (!tree[nodeKey].hasOwnProperty(data[nodeKey])) {
                        if (data.hasOwnProperty(nodeKey)
                            && data[nodeKey] !== data._id
                            && !data.hasOwnProperty('_list')) {
                            tree[nodeKey][data[nodeKey]] = {};
                        }
                    }
                    if (!(data.hasOwnProperty(nodeKey) && data[nodeKey] !== data._id && !data.hasOwnProperty('_list'))) return [3 /*break*/, 5];
                    _a = tree[nodeKey][data[nodeKey]];
                    _b = data._id;
                    return [4 /*yield*/, opts.nodeIdHandler()];
                case 1:
                    _a[_b] = _f.sent();
                    _f.label = 2;
                case 2:
                    _f.trys.push([2, 4, , 5]);
                    return [4 /*yield*/, opts.nodeHandler({
                            name: nodeKey,
                            node: tree[nodeKey],
                            path: nodePath
                        })];
                case 3:
                    _f.sent();
                    return [3 /*break*/, 5];
                case 4:
                    e_1 = _f.sent();
                    console.log(e_1);
                    throw __assign(__assign({}, errors.NODE_HANDLER_ERROR), { reason: e_1.toString() });
                case 5:
                    if (!(data.hasOwnProperty(nodeKey) && data[nodeKey] !== data._id && data.hasOwnProperty('_list'))) return [3 /*break*/, 10];
                    _c = tree[nodeKey];
                    _d = data._id;
                    return [4 /*yield*/, opts.nodeIdHandler()];
                case 6:
                    _c[_d] = _f.sent();
                    _f.label = 7;
                case 7:
                    _f.trys.push([7, 9, , 10]);
                    return [4 /*yield*/, opts.nodeHandler({
                            name: nodeKey,
                            node: (_e = {}, _e[nodeKey] = tree[nodeKey], _e),
                            path: nodePath
                        })];
                case 8:
                    _f.sent();
                    return [3 /*break*/, 10];
                case 9:
                    e_2 = _f.sent();
                    console.log(e_2);
                    throw __assign(__assign({}, errors.NODE_HANDLER_ERROR), { reason: e_2.toString() });
                case 10: return [2 /*return*/, tree];
            }
        });
    });
}
module.exports = {
    TreeController: TreeController
};
