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 logger from "../../../Utils/Logger";
import OneUptimeDate from "../../../../Types/Date";
import { CheckOn, FilterType, } from "../../../../Types/Monitor/CriteriaFilter";
import Typeof from "../../../../Types/Typeof";
import EvaluateOverTime from "./EvaluateOverTime";
import CompareCriteria from "./CompareCriteria";
import CaptureSpan from "../../Telemetry/CaptureSpan";
export default class IncomingRequestCriteria {
    static async isMonitorInstanceCriteriaFilterMet(input) {
        // Server Monitoring Checks
        var _a;
        logger.debug("Checking IncomingRequestCriteria for Monitor: " +
            input.dataToProcess.monitorId.toString());
        logger.debug("Data to process: " + JSON.stringify(input.dataToProcess, null, 2));
        logger.debug("Criteria Filter: " + JSON.stringify(input.criteriaFilter, null, 2));
        let value = input.criteriaFilter.value;
        let overTimeValue = undefined;
        if (input.criteriaFilter.evaluateOverTime &&
            input.criteriaFilter.evaluateOverTimeOptions) {
            try {
                overTimeValue = await EvaluateOverTime.getValueOverTime({
                    projectId: input.dataToProcess.projectId,
                    monitorId: input.dataToProcess.monitorId,
                    evaluateOverTimeOptions: input.criteriaFilter.evaluateOverTimeOptions,
                    metricType: input.criteriaFilter.checkOn,
                });
                if (Array.isArray(overTimeValue) && overTimeValue.length === 0) {
                    overTimeValue = undefined;
                }
            }
            catch (err) {
                logger.error(`Error in getting over time value for ${input.criteriaFilter.checkOn}`);
                logger.error(err);
                overTimeValue = undefined;
            }
        }
        if (input.criteriaFilter.checkOn === CheckOn.IsOnline) {
            const currentIsOnline = overTimeValue ||
                input.dataToProcess.isOnline;
            return CompareCriteria.compareCriteriaBoolean({
                value: currentIsOnline,
                criteriaFilter: input.criteriaFilter,
            });
        }
        // timeout.
        if (input.criteriaFilter.checkOn === CheckOn.IsRequestTimeout) {
            const currentIsTimeout = overTimeValue ||
                input.dataToProcess.isTimeout;
            return CompareCriteria.compareCriteriaBoolean({
                value: currentIsTimeout,
                criteriaFilter: input.criteriaFilter,
            });
        }
        // All incoming request related checks
        if (input.criteriaFilter.checkOn === CheckOn.IncomingRequest) {
            logger.debug("Checking IncomingRequest for Monitor: " +
                input.dataToProcess.monitorId.toString());
            const lastCheckTime = input.dataToProcess.incomingRequestReceivedAt;
            logger.debug("Last Check Time: " + lastCheckTime);
            const differenceInMinutes = OneUptimeDate.getDifferenceInMinutes(lastCheckTime, ((_a = input.dataToProcess) === null || _a === void 0 ? void 0 : _a.checkedAt) ||
                OneUptimeDate.getCurrentDate());
            logger.debug("Difference in minutes: " + differenceInMinutes);
            if (!value) {
                return null;
            }
            if (typeof value === Typeof.String) {
                try {
                    value = parseInt(value);
                }
                catch (err) {
                    logger.error(err);
                    return null;
                }
            }
            if (typeof value !== Typeof.Number) {
                return null;
            }
            if (input.criteriaFilter.filterType === FilterType.RecievedInMinutes) {
                logger.debug("Checking RecievedInMinutes for Monitor: " +
                    input.dataToProcess.monitorId.toString());
                if (value && differenceInMinutes <= value) {
                    logger.debug("RecievedInMinutes for Monitor: " +
                        input.dataToProcess.monitorId.toString() +
                        " is true");
                    return `Incoming request / heartbeat received in ${value} minutes. It was received ${differenceInMinutes} minutes ago.`;
                }
                return null;
            }
            if (input.criteriaFilter.filterType === FilterType.NotRecievedInMinutes) {
                logger.debug("Checking NotRecievedInMinutes for Monitor: " +
                    input.dataToProcess.monitorId.toString());
                if (value && differenceInMinutes > value) {
                    logger.debug("NotRecievedInMinutes for Monitor: " +
                        input.dataToProcess.monitorId.toString() +
                        " is true");
                    return `Incoming request / heartbeat not received in ${value} minutes. It was received ${differenceInMinutes} minutes ago.`;
                }
                return null;
            }
        }
        if (input.criteriaFilter.checkOn === CheckOn.RequestBody) {
            let responseBody = input.dataToProcess.requestBody;
            if (responseBody && typeof responseBody === Typeof.Object) {
                responseBody = JSON.stringify(responseBody);
            }
            if (!responseBody) {
                return null;
            }
            // contains
            if (input.criteriaFilter.filterType === FilterType.Contains) {
                if (value &&
                    responseBody &&
                    responseBody.includes(value)) {
                    return `Request body contains ${value}.`;
                }
                return null;
            }
            if (input.criteriaFilter.filterType === FilterType.NotContains) {
                if (value &&
                    responseBody &&
                    !responseBody.includes(value)) {
                    return `Request body does not contain ${value}.`;
                }
                return null;
            }
        }
        if (input.criteriaFilter.checkOn === CheckOn.RequestHeader) {
            const headerKeys = Object.keys(input.dataToProcess.requestHeaders || {}).map((key) => {
                return key.toLowerCase();
            });
            // contains
            if (input.criteriaFilter.filterType === FilterType.Contains) {
                if (value && headerKeys && headerKeys.includes(value)) {
                    return `Request header contains ${value}.`;
                }
                return null;
            }
            if (input.criteriaFilter.filterType === FilterType.NotContains) {
                if (value && headerKeys && !headerKeys.includes(value)) {
                    return `Request header does not contain ${value}.`;
                }
                return null;
            }
        }
        if (input.criteriaFilter.checkOn === CheckOn.RequestHeaderValue) {
            const headerValues = Object.values(input.dataToProcess.requestHeaders || {}).map((key) => {
                return key.toLowerCase();
            });
            // contains
            if (input.criteriaFilter.filterType === FilterType.Contains) {
                if (value && headerValues && headerValues.includes(value)) {
                    return `Request header value contains ${value}.`;
                }
                return null;
            }
            if (input.criteriaFilter.filterType === FilterType.NotContains) {
                if (value && headerValues && !headerValues.includes(value)) {
                    return `Request header value does not contain ${value}.`;
                }
                return null;
            }
        }
        return null;
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], IncomingRequestCriteria, "isMonitorInstanceCriteriaFilterMet", null);
//# sourceMappingURL=IncomingRequestCriteria.js.map