"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.Resource = exports.genericResourceCall = void 0;
var cnst = require("./const");
var database = require("./database");
var util = require("./utils");
exports.genericResourceCall = function (operation, schema, fields, toQuery, caller) {
    return function (input) { return __awaiter(void 0, void 0, void 0, function () {
        var resource, requestId, _a, context, parsed, info, _b, err_1, error, query, sql;
        return __generator(this, function (_c) {
            switch (_c.label) {
                case 0:
                    resource = caller.name;
                    requestId = input.requestId;
                    caller.logger.debug(__assign(__assign({}, input), { resource: resource,
                        operation: operation }), cnst.RESOURCE_CALL);
                    _a = caller.contextParser(input), context = _a.context, parsed = __rest(_a, ["context"]);
                    if (parsed.error) {
                        caller.logger.error({
                            requestId: requestId,
                            resource: resource,
                            operation: operation,
                            errors: parsed.error
                        }, cnst.CONTEXT_ERRORS);
                        return [2 /*return*/, util.rejectResource(parsed.errorType, parsed.error)];
                    }
                    // set fields to all available by default
                    context.fields = context.fields || fields;
                    info = { error: null, value: null };
                    _c.label = 1;
                case 1:
                    _c.trys.push([1, 3, , 4]);
                    _b = info;
                    return [4 /*yield*/, util.validateOneOrMany(schema, input.payload)];
                case 2:
                    _b.value = _c.sent();
                    return [3 /*break*/, 4];
                case 3:
                    err_1 = _c.sent();
                    info.error = err_1;
                    return [3 /*break*/, 4];
                case 4:
                    error = info.error, query = info.value;
                    if (error) {
                        caller.logger.error({
                            requestId: requestId,
                            resource: resource,
                            operation: operation,
                            error: error
                        }, cnst.VALIDATION_ERROR);
                        return [2 /*return*/, util.rejectResource(cnst.VALIDATION_ERROR, error)];
                    }
                    sql = toQuery(__assign(__assign({}, caller.queryBase()), { query: query,
                        context: context, 
                        // tslint:disable-next-line: no-string-literal
                        hardDelete: !!input["hardDelete"], supportsReturn: caller.supportsReturn }));
                    caller.logger.info({
                        requestId: requestId,
                        resource: resource,
                        operation: operation,
                        sql: sql.toString()
                    }, cnst.RESOURCE_RESPONSE);
                    return [2 /*return*/, util.resolveResource({ sql: sql, context: context, query: query })];
            }
        });
    }); };
};
var Resource = /** @class */ (function () {
    // need to add logger statements throughout
    function Resource(_a) {
        var db = _a.db, st = _a.st, logger = _a.logger, name = _a.name, validator = _a.validator, schemaResource = _a.schemaResource, middlewareFn = _a.middlewareFn, subResourceName = _a.subResourceName, aggregationFn = _a.aggregationFn, geoFields = _a.geoFields, supportsReturn = _a.supportsReturn, pageLimit = _a.pageLimit, redactedFields = _a.redactedFields;
        this.db = db;
        this.st = st;
        this.logger = logger;
        this.name = name;
        this.validator = validator;
        this.schemaResource = schemaResource;
        this.middlewareFn = middlewareFn;
        this.hasSubquery = !!subResourceName;
        this.subResourceName = subResourceName;
        this.aggregationFn = aggregationFn;
        this.geoFields = geoFields;
        this.supportsReturn = supportsReturn;
        this.pageLimit = pageLimit;
        var _b = util.validationExpander(validator, redactedFields || []), schema = _b.schema, report = _b.report, meta = _b.meta;
        this.schema = schema;
        this.report = report;
        this.meta = meta;
        // these generic calls need to be defined in the contstructor so they only get called once
        var generics = {
            create: exports.genericResourceCall(cnst.CREATE, schema.create, Object.keys(report.create), database.toCreateQuery, this),
            read: exports.genericResourceCall(cnst.READ, schema.read, Object.keys(report.read), database.toReadQuery, this),
            update: exports.genericResourceCall(cnst.UPDATE, schema.update, Object.keys(report.update), database.toUpdateQuery(this.meta.uniqueKeyComponents), this),
            "delete": exports.genericResourceCall(cnst.DELETE, schema["delete"], Object.keys(report["delete"]), database.toDeleteQuery(this.meta.uniqueKeyComponents), this)
        };
        this.generics = generics;
        // this.middleware || for read && search
        // this.permissions (CRUD, hard/soft delete)
    }
    Resource.prototype.queryBase = function () {
        return {
            db: this.db,
            st: this.st,
            resource: this.name,
            schemaResource: this.schemaResource
        };
    };
    Resource.prototype.contextParser = function (input) {
        var context = __assign({}, cnst.SEARCH_QUERY_CONTEXT);
        var rejection = {
            errorType: undefined,
            error: undefined
        };
        if (input.context) {
            var result = util.queryContextParser(this.validator, input.context, input.apiType);
            if (result.errors.length) {
                rejection = util.rejectResource(cnst.CONTEXT_ERRORS, result.errors);
            }
            // returned context is mutated if passed
            context = result.context;
        }
        return __assign(__assign({}, rejection), { context: context });
    };
    // these generic calls need to be defined in the contstructor so they only get called once
    Resource.prototype.create = function (input) {
        return this.generics.create(input);
    };
    Resource.prototype.read = function (input) {
        return this.generics.read(input);
    };
    Resource.prototype.update = function (input) {
        return this.generics.update(input);
    };
    Resource.prototype["delete"] = function (input) {
        return this.generics["delete"](input);
    };
    Resource.prototype.search = function (input, _a) {
        if (_a === void 0) { _a = {}; }
        var subqueryContext = _a.subqueryContext, subqueryOptions = __rest(_a, ["subqueryContext"]);
        return __awaiter(this, void 0, void 0, function () {
            var requestId, operation, _b, context, parsed, stringValues, _c, errors, components, sql;
            return __generator(this, function (_d) {
                switch (_d.label) {
                    case 0:
                        requestId = input.requestId;
                        operation = !!subqueryContext ? cnst.SUBQUERY : cnst.SEARCH;
                        this.logger.debug(__assign(__assign({}, input), { resource: this.name, operation: operation }), cnst.RESOURCE_CALL);
                        _b = this.contextParser(input), context = _b.context, parsed = __rest(_b, ["context"]);
                        // context.fields = !!subqueryContext && context.fields ? context.fields : Object.keys(this.report.search);
                        context.fields = context.fields || Object.keys(this.report.search);
                        context.limit =
                            context.limit && context.limit <= this.pageLimit
                                ? context.limit
                                : this.pageLimit;
                        if (parsed.error) {
                            this.logger.error({
                                requestId: requestId,
                                resource: this.name,
                                operation: operation,
                                errors: parsed.error
                            }, cnst.CONTEXT_ERRORS);
                            return [2 /*return*/, util.rejectResource(parsed.errorType, parsed.error)];
                        }
                        stringValues = util.stringValues(context.seperator);
                        // if subqueryContext -- delete most the context keys
                        if (subqueryContext) {
                            delete context.seperator;
                            delete context.orderBy;
                            delete context.distinct;
                            delete context.page;
                            delete context.limit;
                            // TODO: what about context.fields? confirm this works correctly
                        }
                        // standardize GRAPHQL & GRPC inputs to REST string input
                        input.payload = stringValues(input.payload);
                        return [4 /*yield*/, this.meta.searchQueryParser(
                            // if middlewareFn -- serialize the Object.values to all be strings
                            this.middlewareFn ? this.middlewareFn(input.payload) : input.payload, input.apiType, context)];
                    case 1:
                        _c = _d.sent(), errors = _c.errors, components = _c.components;
                        if (errors.length) {
                            this.logger.error({
                                requestId: requestId,
                                resource: this.name,
                                operation: cnst.DELETE,
                                errors: errors
                            }, cnst.VALIDATION_ERROR);
                            return [2 /*return*/, util.rejectResource(cnst.CONTEXT_ERRORS, errors)];
                        }
                        sql = database.toSearchQuery(__assign(__assign({}, this.queryBase()), { context: context,
                            components: components,
                            subqueryOptions: subqueryOptions, geoFields: this.geoFields, supportsReturn: true }));
                        this.logger.info({
                            requestId: requestId,
                            resource: this.name,
                            operation: operation,
                            sql: sql.toString()
                        }, cnst.RESOURCE_RESPONSE);
                        return [2 /*return*/, util.resolveResource({ sql: sql, query: components, context: context })];
                }
            });
        });
    };
    Resource.prototype.transformRecords = function (records) {
        var _this = this;
        var output = records;
        var stDataAsWkt = this.db.client.config.client === "pg";
        // transform geo fields to geoJSON
        if (stDataAsWkt && records.length) {
            var geoFields_1 = Object.keys(records[0]).filter(function (field) {
                return _this.report.search[field] && _this.report.search[field].geoqueryType;
            });
            var transform = function (record) {
                geoFields_1.forEach(function (geoField) { return (record[geoField] = util.wktToGeoJSON(record[geoField])); });
                return record;
            };
            if (geoFields_1.length) {
                output = records.map(transform);
            }
        }
        return output;
    };
    return Resource;
}());
exports.Resource = Resource;
//# sourceMappingURL=class.js.map