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 CaptureSpan from "../../Telemetry/CaptureSpan";
export default class IncomingEmailCriteria {
    static async isMonitorInstanceCriteriaFilterMet(input) {
        // Incoming Email Monitoring Checks
        logger.debug("Checking IncomingEmailCriteria 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;
        const emailData = input.dataToProcess;
        // Check on Email Received time
        if (input.criteriaFilter.checkOn === CheckOn.EmailReceivedAt) {
            logger.debug("Checking EmailReceivedAt for Monitor: " +
                input.dataToProcess.monitorId.toString());
            const lastEmailTime = emailData.emailReceivedAt;
            logger.debug("Last Email Time: " + lastEmailTime);
            const differenceInMinutes = OneUptimeDate.getDifferenceInMinutes(lastEmailTime, emailData.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 `Email 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 `Email not received in ${value} minutes. It was received ${differenceInMinutes} minutes ago.`;
                }
                return null;
            }
        }
        // Check on Email Subject
        if (input.criteriaFilter.checkOn === CheckOn.EmailSubject &&
            !emailData.onlyCheckForIncomingEmailReceivedAt) {
            const subject = emailData.emailSubject || "";
            return this.evaluateStringCriteria(subject, input.criteriaFilter, "Email subject");
        }
        // Check on Email From
        if (input.criteriaFilter.checkOn === CheckOn.EmailFrom &&
            !emailData.onlyCheckForIncomingEmailReceivedAt) {
            const from = emailData.emailFrom || "";
            return this.evaluateStringCriteria(from, input.criteriaFilter, "Email from");
        }
        // Check on Email Body
        if (input.criteriaFilter.checkOn === CheckOn.EmailBody &&
            !emailData.onlyCheckForIncomingEmailReceivedAt) {
            const body = emailData.emailBody || "";
            return this.evaluateStringCriteria(body, input.criteriaFilter, "Email body");
        }
        // Check on Email To
        if (input.criteriaFilter.checkOn === CheckOn.EmailTo &&
            !emailData.onlyCheckForIncomingEmailReceivedAt) {
            const to = emailData.emailTo || "";
            return this.evaluateStringCriteria(to, input.criteriaFilter, "Email to");
        }
        return null;
    }
    /**
     * Evaluate string criteria filters
     */
    static evaluateStringCriteria(fieldValue, criteriaFilter, fieldName) {
        const value = criteriaFilter.value;
        if (criteriaFilter.filterType === FilterType.Contains) {
            if (value &&
                fieldValue.toLowerCase().includes(value.toLowerCase())) {
                return `${fieldName} contains "${value}".`;
            }
            return null;
        }
        if (criteriaFilter.filterType === FilterType.NotContains) {
            if (value &&
                !fieldValue.toLowerCase().includes(value.toLowerCase())) {
                return `${fieldName} does not contain "${value}".`;
            }
            return null;
        }
        if (criteriaFilter.filterType === FilterType.EqualTo) {
            if (value &&
                fieldValue.toLowerCase() === value.toLowerCase()) {
                return `${fieldName} equals "${value}".`;
            }
            return null;
        }
        if (criteriaFilter.filterType === FilterType.NotEqualTo) {
            if (value &&
                fieldValue.toLowerCase() !== value.toLowerCase()) {
                return `${fieldName} does not equal "${value}".`;
            }
            return null;
        }
        if (criteriaFilter.filterType === FilterType.StartsWith) {
            if (value &&
                fieldValue.toLowerCase().startsWith(value.toLowerCase())) {
                return `${fieldName} starts with "${value}".`;
            }
            return null;
        }
        if (criteriaFilter.filterType === FilterType.EndsWith) {
            if (value &&
                fieldValue.toLowerCase().endsWith(value.toLowerCase())) {
                return `${fieldName} ends with "${value}".`;
            }
            return null;
        }
        if (criteriaFilter.filterType === FilterType.IsEmpty) {
            if (!fieldValue || fieldValue.trim() === "") {
                return `${fieldName} is empty.`;
            }
            return null;
        }
        if (criteriaFilter.filterType === FilterType.IsNotEmpty) {
            if (fieldValue && fieldValue.trim() !== "") {
                const truncatedValue = fieldValue.length > 500
                    ? fieldValue.substring(0, 500) + "..."
                    : fieldValue;
                return `${fieldName} is not empty. Value: ${truncatedValue}`;
            }
            return null;
        }
        return null;
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], IncomingEmailCriteria, "isMonitorInstanceCriteriaFilterMet", null);
//# sourceMappingURL=IncomingEmailCriteria.js.map