"use strict";
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 __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
exports.__esModule = true;
exports.prepare = void 0;
var fs_1 = require("fs");
var protoLoader = require("@grpc/proto-loader");
var change_case_1 = require("change-case");
var grpc = require("@grpc/grpc-js");
var class_1 = require("./class");
var const_1 = require("./const");
var database_1 = require("./database");
var dialects_1 = require("./dialects");
var graphql_1 = require("./graphql");
var grpc_1 = require("./grpc");
var rest_1 = require("./rest");
var utils_1 = require("./utils");
var PROTO_PATH = __dirname + "/service.proto";
exports.prepare = function (_a) {
    var db = _a.db, st = _a.st, metadata = _a.metadata, logger = _a.logger, middleware = _a.middleware, supportsReturn = _a.supportsReturn, complexResources = _a.complexResources, hardDelete = _a.hardDelete, permissions = _a.permissions, pageLimit = _a.pageLimit, grpcPort = _a.grpcPort, redactedFields = _a.redactedFields;
    return __awaiter(void 0, void 0, void 0, function () {
        var _b, dbSurveyQuery, versionQuery, joiBase, toSchemaScalar, toProtoScalar, dbGeometryColumns, getRows, _c, dbResourceRawRows, dbVersionRawRows, fields, REGEX_LEGAL_SDL, flagNonSupportedSchemaChars, problemResources, _d, validators, dbResources, mapSchemaResources, geoFields, _results, geoRows, fn, Resources, AppModule, AppShortName, _e, protoString, grpcMethods, _f, appRouter, serviceRouter, packageDefinition, protoService, grpcService;
        return __generator(this, function (_g) {
            switch (_g.label) {
                case 0:
                    _b = dialects_1.getDatabaseResources({
                        db: db
                    }), dbSurveyQuery = _b.dbSurveyQuery, versionQuery = _b.versionQuery, joiBase = _b.joiBase, toSchemaScalar = _b.toSchemaScalar, toProtoScalar = _b.toProtoScalar, dbGeometryColumns = _b.dbGeometryColumns;
                    getRows = function (item) { return (item.hasOwnProperty("rows") ? item.rows : item); };
                    return [4 /*yield*/, Promise.all([
                            db.raw(dbSurveyQuery),
                            db.raw(versionQuery),
                        ]).then(function (payload) { return payload.map(getRows); })];
                case 1:
                    _c = _g.sent(), dbResourceRawRows = _c[0], dbVersionRawRows = _c[1];
                    metadata.db_info = {
                        dialect: db.client.config.client,
                        version: dbVersionRawRows[0].db_version,
                        pageLimit: pageLimit
                    };
                    fields = ["resource_schema", "resource_name", "resource_column_name"];
                    REGEX_LEGAL_SDL = /[0-9a-zA-Z_]+/g;
                    flagNonSupportedSchemaChars = function (record) {
                        return Object.entries(record).filter(function (_a) {
                            var key = _a[0], value = _a[1];
                            return (fields.includes(key) &&
                                value.toString().length &&
                                value.toString().match(REGEX_LEGAL_SDL).length > 1);
                        }).length > 0;
                    };
                    problemResources = dbResourceRawRows.filter(flagNonSupportedSchemaChars);
                    if (!!problemResources.length) {
                        logger.fatal({
                            summary: "unsupported character breaking GraphqL Schema",
                            detail: const_1.UNSUPPORTED_CHARACTER_IN_DB,
                            problemResources: problemResources,
                            fieldsOfConcern: fields
                        }, const_1.STARTUP_FAILED);
                        process.exit(1);
                    }
                    return [4 /*yield*/, utils_1.genDatabaseResourceValidators({
                            db: db,
                            dbResourceRawRows: dbResourceRawRows,
                            joiBase: joiBase
                        })];
                case 2:
                    _d = _g.sent(), validators = _d.validators, dbResources = _d.dbResources;
                    // once validators have been created -- remove any redacted fields.
                    // prevents publication to GraphQL, gRPC & REST responses.
                    Object.entries(redactedFields).forEach(function (_a) {
                        var resourceName = _a[0], columns = _a[1];
                        columns.forEach(function (column) {
                            if (dbResources[resourceName] && dbResources[resourceName][column]) {
                                delete dbResources[resourceName][column];
                            }
                        });
                    });
                    mapSchemaResources = dbResourceRawRows.reduce(function (resourceMap, _a) {
                        var _b;
                        var resource_schema = _a.resource_schema, resource_name = _a.resource_name;
                        return (__assign(__assign({}, resourceMap), (_b = {}, _b[resource_schema + "_" + resource_name] = {
                            resource_schema: resource_schema,
                            resource_name: resource_name
                        }, _b)));
                    }, {});
                    geoFields = {};
                    if (!(dbGeometryColumns && mapSchemaResources.public_geometry_columns)) return [3 /*break*/, 4];
                    return [4 /*yield*/, db.raw(dbGeometryColumns)];
                case 3:
                    _results = _g.sent();
                    geoRows = _results.hasOwnProperty("rows") ? _results.rows : _results;
                    fn = function (accum, _a) {
                        var type = _a.type, srid = _a.srid, curr = __rest(_a, ["type", "srid"]);
                        var resourceName = curr.resource_schema + "_" + curr.resource_name;
                        if (!accum[resourceName]) {
                            accum[resourceName] = {};
                        }
                        accum[resourceName][curr.resource_column_name] = {
                            type: type,
                            srid: srid
                        };
                        return accum;
                    };
                    geoFields = geoRows.reduce(fn, {});
                    _g.label = 4;
                case 4:
                    Resources = Object.entries(validators).map(function (_a) {
                        var name = _a[0], validator = _a[1];
                        return [
                            name,
                            new class_1.Resource({
                                db: db,
                                st: st,
                                logger: logger,
                                name: name,
                                validator: validator,
                                schemaResource: mapSchemaResources[name],
                                middlewareFn: middleware && middleware[name] ? middleware[name] : undefined,
                                geoFields: geoFields[name] || undefined,
                                supportsReturn: supportsReturn,
                                pageLimit: pageLimit,
                                redactedFields: redactedFields[name] || []
                            }),
                        ];
                    });
                    // build the complex resources based on the provided configs
                    (complexResources || []).forEach(function (_a) {
                        var topResourceName = _a.topResourceName, subResourceName = _a.subResourceName, calculatedFields = _a.calculatedFields, groupBy = _a.groupBy;
                        // confirm they exist else
                        if (!dbResources[topResourceName] || !dbResources[subResourceName]) {
                            logger.fatal({
                                summary: "bad configuration",
                                detail: const_1.BAD_CONFIG_COMPLEX_RESOURCE,
                                complex_query: { topResourceName: topResourceName, subResourceName: subResourceName }
                            }, const_1.STARTUP_FAILED);
                            process.exit(1);
                        }
                        var name = topResourceName + ":" + subResourceName;
                        Resources.push([
                            name,
                            new class_1.Resource({
                                db: db,
                                st: st,
                                logger: logger,
                                name: name,
                                validator: validators[topResourceName],
                                schemaResource: mapSchemaResources[topResourceName],
                                middlewareFn: middleware && middleware[name] ? middleware[name] : undefined,
                                subResourceName: subResourceName,
                                aggregationFn: database_1.aggregationFnBuilder(db)(calculatedFields, groupBy),
                                geoFields: geoFields[name] || undefined,
                                supportsReturn: supportsReturn,
                                pageLimit: pageLimit,
                                redactedFields: redactedFields[name] || []
                            }),
                        ]);
                    });
                    return [4 /*yield*/, graphql_1.gqlModule({
                            dbResources: dbResources,
                            Resources: Resources,
                            toSchemaScalar: toSchemaScalar,
                            hardDelete: hardDelete,
                            metadata: metadata,
                            supportsReturn: supportsReturn,
                            permissions: permissions
                        })];
                case 5:
                    AppModule = (_g.sent()).AppModule;
                    AppShortName = change_case_1.pascalCase(metadata.appShortName);
                    return [4 /*yield*/, grpc_1.grpcModule({
                            dbResources: dbResources,
                            Resources: Resources,
                            toProtoScalar: toProtoScalar,
                            hardDelete: hardDelete,
                            metadata: metadata,
                            supportsReturn: supportsReturn,
                            permissions: permissions,
                            AppShortName: AppShortName,
                            logger: logger
                        })];
                case 6:
                    _e = _g.sent(), protoString = _e.protoString, grpcMethods = _e.grpcMethods;
                    return [4 /*yield*/, rest_1.serviceRouters({
                            db: db,
                            st: st,
                            logger: logger,
                            metadata: metadata,
                            validators: validators,
                            dbResources: dbResources,
                            dbResourceRawRows: dbResourceRawRows,
                            Resources: Resources,
                            toSchemaScalar: toSchemaScalar,
                            protoString: protoString,
                            hardDelete: hardDelete,
                            supportsReturn: supportsReturn,
                            permissions: permissions
                        })];
                case 7:
                    _f = _g.sent(), appRouter = _f.appRouter, serviceRouter = _f.serviceRouter;
                    // setup grpc service
                    // write schema to proto file with specific path
                    fs_1.writeFileSync(PROTO_PATH, protoString);
                    packageDefinition = protoLoader.loadSync(PROTO_PATH, {
                        keepCase: true,
                        longs: String,
                        enums: String,
                        bytes: Array
                    });
                    protoService = grpc.loadPackageDefinition(packageDefinition).service;
                    grpcService = new grpc.Server();
                    grpcService.addService(protoService[AppShortName].service, grpcMethods);
                    grpcService.bindAsync("0.0.0.0:" + grpcPort, grpc.ServerCredentials.createInsecure(), function (err, port) {
                        if (err) {
                            logger.fatal({
                                summary: "gRPC service not bound to port",
                                detail: const_1.BAD_GRPC_BIND,
                                error: err,
                                port: port
                            }, const_1.STARTUP_FAILED);
                            process.exit(1);
                        }
                        grpcService.start();
                    });
                    return [2 /*return*/, { appRouter: appRouter, serviceRouter: serviceRouter, AppModule: AppModule, AppShortName: AppShortName, grpcService: grpcService }];
            }
        });
    });
};
//# sourceMappingURL=setup.js.map