var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
import JsonToCsv from "./JsonToCsv";
import logger, { getLogAttributesFromRequest } from "./Logger";
import AnalyticsDataModel from "../../Models/AnalyticsModels/AnalyticsBaseModel/AnalyticsBaseModel";
import BaseModel from "../../Models/DatabaseModels/DatabaseBaseModel/DatabaseBaseModel";
import FileModel from "../../Models/DatabaseModels/DatabaseBaseModel/FileModel";
import { DEFAULT_LIMIT } from "../../Types/Database/LimitMax";
import Exception from "../../Types/Exception/Exception";
import ListData from "../../Types/ListData";
import PositiveNumber from "../../Types/PositiveNumber";
import CaptureSpan from "./Telemetry/CaptureSpan";
export default class Response {
    static sendEmptySuccessResponse(_req, res) {
        const oneUptimeResponse = res;
        oneUptimeResponse.status(200).send({});
    }
    static sendFileByPath(_req, res, path) {
        Response.setNoCacheHeaders(res);
        res.sendFile(path);
    }
    static sendCustomResponse(_req, res, statusCode, body, headers) {
        var _a;
        const oneUptimeResponse = res;
        if (headers) {
            Response.setNoCacheHeaders(oneUptimeResponse);
            for (const key in headers) {
                oneUptimeResponse.set(key, ((_a = headers[key]) === null || _a === void 0 ? void 0 : _a.toString()) || "");
            }
        }
        oneUptimeResponse.status(statusCode).send(body);
    }
    static async sendFileResponse(_req, res, file) {
        /** Create read stream */
        const oneUptimeResponse = res;
        /** Set the proper content type */
        oneUptimeResponse.set("Content-Type", file.fileType);
        oneUptimeResponse.status(200);
        /** Return response */
        // readstream.pipe(res);
        oneUptimeResponse.send(file.file);
    }
    static render(_req, res, path, vars) {
        const oneUptimeResponse = res;
        oneUptimeResponse.render(path, vars);
    }
    static sendErrorResponse(_req, res, error) {
        const oneUptimeResponse = res;
        oneUptimeResponse.logBody = { message: error.message }; // To be used in 'auditLog' middleware to log response data;
        const status = error.code || 500;
        const message = error.message || "Server Error";
        logger.error(error, getLogAttributesFromRequest(_req));
        oneUptimeResponse.status(status).send({ message });
    }
    static sendEntityArrayResponse(req, res, list, count, modelType, options) {
        if (!(count instanceof PositiveNumber)) {
            count = new PositiveNumber(count);
        }
        let jsonArray = [];
        const model = new modelType();
        if (model instanceof BaseModel) {
            jsonArray = BaseModel.toJSONArray(list, modelType);
        }
        if (model instanceof AnalyticsDataModel) {
            jsonArray = AnalyticsDataModel.toJSONArray(list, modelType);
        }
        return this.sendJsonArrayResponse(req, res, jsonArray, count, options);
    }
    static sendEntityResponse(req, res, item, modelType, options) {
        let response = {};
        if (item && item instanceof BaseModel) {
            response = BaseModel.toJSON(item, modelType);
        }
        if (item && item instanceof AnalyticsDataModel) {
            response = AnalyticsDataModel.toJSON(item, modelType);
        }
        if (options === null || options === void 0 ? void 0 : options.miscData) {
            response["_miscData"] = options.miscData;
        }
        return this.sendJsonObjectResponse(req, res, response);
    }
    static redirect(_req, res, to) {
        return res.redirect(to.toString());
    }
    static sendJsonArrayResponse(req, res, list, count, options) {
        const oneUptimeRequest = req;
        const oneUptimeResponse = res;
        const listData = new ListData({
            data: [],
            count: new PositiveNumber(0),
            skip: new PositiveNumber(0),
            limit: new PositiveNumber(0),
            hasMore: options === null || options === void 0 ? void 0 : options.hasMore,
        });
        if (!list) {
            list = [];
        }
        listData.data = list;
        if (count) {
            listData.count = count;
        }
        else if (list) {
            listData.count = new PositiveNumber(list.length);
        }
        if (oneUptimeRequest.query["skip"]) {
            listData.skip = new PositiveNumber(parseInt(oneUptimeRequest.query["skip"].toString()));
        }
        if (oneUptimeRequest.query["limit"]) {
            listData.limit = new PositiveNumber(parseInt(oneUptimeRequest.query["limit"].toString()));
        }
        else {
            listData.limit = new PositiveNumber(DEFAULT_LIMIT);
        }
        if (oneUptimeRequest.query["output-type"] === "csv") {
            const csv = JsonToCsv.ToCsv(listData.data);
            oneUptimeResponse.status(200).send(csv);
        }
        else {
            oneUptimeResponse.status(200).send(listData);
            oneUptimeResponse.logBody = listData.toJSON(); // To be used in 'auditLog' middleware to log response data;
        }
    }
    static sendJsonObjectResponse(req, res, item, options) {
        const oneUptimeRequest = req;
        const oneUptimeResponse = res;
        if (oneUptimeRequest.query["output-type"] === "csv") {
            const csv = JsonToCsv.ToCsv([item]);
            oneUptimeResponse.status(200).send(csv);
            return;
        }
        oneUptimeResponse.logBody = item;
        oneUptimeResponse
            .status((options === null || options === void 0 ? void 0 : options.statusCode) ? options === null || options === void 0 ? void 0 : options.statusCode.toNumber() : 200)
            .send(item);
    }
    static sendTextResponse(_req, res, text) {
        const oneUptimeResponse = res;
        oneUptimeResponse.logBody = { text: text };
        oneUptimeResponse.status(200).send(text);
    }
    static sendHtmlResponse(_req, res, html) {
        const oneUptimeResponse = res;
        oneUptimeResponse.logBody = { html: html };
        oneUptimeResponse.writeHead(200, { "Content-Type": "text/html" });
        oneUptimeResponse.end(html);
    }
    static sendMarkdownResponse(_req, res, html) {
        return Response.sendHtmlResponse(_req, res, html);
    }
    static sendXmlResponse(_req, res, xml) {
        const oneUptimeResponse = res;
        oneUptimeResponse.logBody = { xml: xml };
        oneUptimeResponse.writeHead(200, { "Content-Type": "text/xml" });
        oneUptimeResponse.end(xml);
    }
    static sendJavaScriptResponse(_req, res, javascript) {
        const oneUptimeResponse = res;
        oneUptimeResponse.logBody = { javascript: javascript };
        oneUptimeResponse.writeHead(200, { "Content-Type": "text/javascript" });
        oneUptimeResponse.end(javascript);
    }
    static setNoCacheHeaders(res) {
        const oneUptimeResponse = res;
        oneUptimeResponse.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        oneUptimeResponse.setHeader("Pragma", "no-cache");
        oneUptimeResponse.setHeader("Expires", "0");
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object]),
    __metadata("design:returntype", void 0)
], Response, "sendEmptySuccessResponse", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, String]),
    __metadata("design:returntype", void 0)
], Response, "sendFileByPath", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, Number, Object, Object]),
    __metadata("design:returntype", void 0)
], Response, "sendCustomResponse", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, FileModel]),
    __metadata("design:returntype", Promise)
], Response, "sendFileResponse", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, String, Object]),
    __metadata("design:returntype", void 0)
], Response, "render", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, Exception]),
    __metadata("design:returntype", void 0)
], Response, "sendErrorResponse", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, Array, Object, Object, Object]),
    __metadata("design:returntype", void 0)
], Response, "sendEntityArrayResponse", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, Object, Object, Object]),
    __metadata("design:returntype", void 0)
], Response, "sendEntityResponse", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, Object]),
    __metadata("design:returntype", void 0)
], Response, "redirect", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, Array,
        PositiveNumber, Object]),
    __metadata("design:returntype", void 0)
], Response, "sendJsonArrayResponse", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, Object, Object]),
    __metadata("design:returntype", void 0)
], Response, "sendJsonObjectResponse", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, String]),
    __metadata("design:returntype", void 0)
], Response, "sendTextResponse", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, String]),
    __metadata("design:returntype", void 0)
], Response, "sendHtmlResponse", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, String]),
    __metadata("design:returntype", void 0)
], Response, "sendMarkdownResponse", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, String]),
    __metadata("design:returntype", void 0)
], Response, "sendXmlResponse", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object, String]),
    __metadata("design:returntype", void 0)
], Response, "sendJavaScriptResponse", null);
//# sourceMappingURL=Response.js.map