import { Green } from "../../Types/BrandColors";
import OneUptimeDate from "../../Types/Date";
import ObjectID from "../../Types/ObjectID";
import UptimePrecision from "../../Types/StatusPage/UptimePrecision";
export default class UptimeUtil {
    /**
     * This function, `getMonitorEventsForId`, takes a `monitorId` as an argument and returns an array of `MonitorEvent` objects.
     * @param {ObjectID} monitorId - The ID of the monitor for which events are to be fetched.
     * @returns {Array<MonitorEvent>} - An array of `MonitorEvent` objects.
     */
    static getMonitorEventsForId(monitorId, statusTimelineItems) {
        // Initialize an empty array to store the monitor events.
        var _a, _b, _c, _d, _e, _f;
        // make sure items are sorted by start date.
        let items = [...statusTimelineItems];
        items = items.sort((a, b) => {
            if (!a.startsAt || !b.startsAt) {
                return 0;
            }
            if (OneUptimeDate.isAfter(a.startsAt, b.startsAt)) {
                return 1;
            }
            if (OneUptimeDate.isAfter(b.startsAt, a.startsAt)) {
                return -1;
            }
            return 0;
        });
        const eventList = [];
        const monitorEvents = items.filter((item) => {
            var _a;
            return ((_a = item.monitorId) === null || _a === void 0 ? void 0 : _a.toString()) === monitorId.toString();
        });
        // Loop through the items in the props object.
        for (let i = 0; i < monitorEvents.length; i++) {
            // If the current item is null or undefined, skip to the next iteration.
            if (!monitorEvents[i]) {
                continue;
            }
            // Set the start date of the event to the creation date of the current item. If it doesn't exist, use the current date.
            const startDate = monitorEvents[i].startsAt || OneUptimeDate.getCurrentDate();
            // Initialize the end date as the current date.
            let endDate = monitorEvents[i].endsAt;
            if (!endDate) {
                // check if there's next event, if there is, set the end date to the start date of the next event.
                if (i < monitorEvents.length - 1) {
                    endDate = monitorEvents[i + 1].startsAt;
                }
                else {
                    endDate = OneUptimeDate.getCurrentDate();
                }
            }
            // Push a new MonitorEvent object to the eventList array with properties from the current item and calculated dates.
            eventList.push({
                startDate: startDate,
                endDate: endDate,
                label: ((_b = (_a = monitorEvents[i]) === null || _a === void 0 ? void 0 : _a.monitorStatus) === null || _b === void 0 ? void 0 : _b.name) || "Operational",
                priority: ((_d = (_c = monitorEvents[i]) === null || _c === void 0 ? void 0 : _c.monitorStatus) === null || _d === void 0 ? void 0 : _d.priority) || 0,
                color: ((_f = (_e = monitorEvents[i]) === null || _e === void 0 ? void 0 : _e.monitorStatus) === null || _f === void 0 ? void 0 : _f.color) || Green,
                monitorId: monitorEvents[i].monitorId,
                eventStatusId: monitorEvents[i].monitorStatus.id,
            });
        }
        // Return the populated eventList array.
        return eventList;
    }
    static getNonOverlappingMonitorEvents(items) {
        var _a;
        const monitorEventList = this.getMonitorEvents(items);
        const eventList = [];
        for (let i = 0; i < monitorEventList.length; i++) {
            // if this event starts after the last event, then add it to the list directly.
            const monitorEvent = monitorEventList[i];
            if (!monitorEvent.endDate) {
                // if this is the last event then set endDate to current date.
                // otherwise set it to start date of next event.
                if (i === monitorEventList.length - 1) {
                    monitorEvent.endDate = OneUptimeDate.getCurrentDate();
                }
                else {
                    monitorEvent.endDate =
                        monitorEventList[i + 1].startDate ||
                            OneUptimeDate.getCurrentDate();
                }
            }
            if (eventList.length === 0 ||
                OneUptimeDate.isAfter(monitorEvent.startDate, eventList[eventList.length - 1].endDate) ||
                OneUptimeDate.isEqualBySeconds(monitorEvent.startDate, eventList[eventList.length - 1].endDate)) {
                eventList.push(monitorEvent);
                continue;
            }
            // if this event starts before the last event, then we need to check if it ends before the last event. If it does, then we can skip this event if the monitrEvent is of lower priority than the last event. If it is of higher priority, then we need to add it to the list and remove the last event from the list.
            if (OneUptimeDate.isBefore(monitorEvent.startDate, eventList[eventList.length - 1].endDate)) {
                let isEndDateOfCurrenteventAfterLastEvent = false;
                if (eventList[eventList.length - 1] &&
                    ((_a = eventList[eventList.length - 1]) === null || _a === void 0 ? void 0 : _a.endDate)) {
                    isEndDateOfCurrenteventAfterLastEvent =
                        OneUptimeDate.isAfter(monitorEvent.endDate, eventList[eventList.length - 1].endDate) ||
                            OneUptimeDate.isEqualBySeconds(monitorEvent.endDate, eventList[eventList.length - 1].endDate);
                }
                if (monitorEvent.priority > eventList[eventList.length - 1].priority ||
                    isEndDateOfCurrenteventAfterLastEvent) {
                    // end the last event at the start of this event.
                    const tempLastEvent = Object.assign({}, eventList[eventList.length - 1]);
                    eventList[eventList.length - 1].endDate = monitorEvent.startDate;
                    eventList.push(monitorEvent);
                    // if the monitorEvent endDate is before the end of the last event, then we need to add the end of the last event to the list.
                    if (OneUptimeDate.isBefore(monitorEvent.endDate, tempLastEvent.endDate)) {
                        eventList.push({
                            startDate: monitorEvent.endDate,
                            endDate: tempLastEvent.endDate,
                            label: tempLastEvent.label,
                            priority: tempLastEvent.priority,
                            color: tempLastEvent.color,
                            eventStatusId: tempLastEvent.eventStatusId,
                        });
                    }
                }
                continue;
            }
        }
        return eventList;
    }
    static getMonitorEvents(items) {
        var _a;
        // get all distinct monitor ids.
        const monitorIds = [];
        for (let i = 0; i < items.length; i++) {
            if (!items[i]) {
                continue;
            }
            const monitorId = (_a = items[i].monitorId) === null || _a === void 0 ? void 0 : _a.toString();
            if (!monitorId) {
                continue;
            }
            if (!monitorIds.find((item) => {
                return item.toString() === monitorId;
            })) {
                monitorIds.push(new ObjectID(monitorId));
            }
        }
        const eventList = [];
        // convert data to events.
        for (const monitorId of monitorIds) {
            const monitorEvents = this.getMonitorEventsForId(monitorId, items);
            eventList.push(...monitorEvents);
        }
        // sort event list by start date.
        eventList.sort((a, b) => {
            if (OneUptimeDate.isAfter(a.startDate, b.startDate)) {
                return 1;
            }
            if (OneUptimeDate.isAfter(b.startDate, a.startDate)) {
                return -1;
            }
            return 0;
        });
        return [...eventList];
    }
    static getTotalDowntimeInSeconds(monitorStatusTimelines, downtimeMonitorStatuses) {
        const monitorEvents = this.getNonOverlappingMonitorEvents(monitorStatusTimelines);
        // sort these by start date,
        monitorEvents.sort((a, b) => {
            if (OneUptimeDate.isAfter(a.startDate, b.startDate)) {
                return 1;
            }
            if (OneUptimeDate.isAfter(b.startDate, a.startDate)) {
                return -1;
            }
            return 0;
        });
        // calculate number of seconds between start of first event to date time now.
        let totalSecondsInTimePeriod = 0;
        if (monitorEvents.length === 0) {
            return {
                totalDowntimeInSeconds: 0,
                totalSecondsInTimePeriod: 1,
            };
        }
        if (OneUptimeDate.isAfter(monitorEvents[0].startDate, OneUptimeDate.getCurrentDate())) {
            return {
                totalDowntimeInSeconds: 0,
                totalSecondsInTimePeriod: 1,
            };
        }
        totalSecondsInTimePeriod =
            OneUptimeDate.getSecondsBetweenDates(monitorEvents[0].startDate, OneUptimeDate.getCurrentDate()) || 1;
        // get order of operational state.
        // if the event belongs to less than operationalStatePriority, then add the seconds to the total seconds.
        let totalDowntime = 0;
        for (const monitorEvent of monitorEvents) {
            const isDowntimeEvent = Boolean(downtimeMonitorStatuses.find((item) => {
                var _a;
                return ((_a = item.id) === null || _a === void 0 ? void 0 : _a.toString()) === monitorEvent.eventStatusId.toString();
            }));
            if (isDowntimeEvent) {
                totalDowntime += OneUptimeDate.getSecondsBetweenDates(monitorEvent.startDate, monitorEvent.endDate);
            }
        }
        return {
            totalDowntimeInSeconds: totalDowntime,
            totalSecondsInTimePeriod,
        };
    }
    static roundToPrecision(data) {
        const { number, precision } = data;
        if (precision === UptimePrecision.NO_DECIMAL) {
            return Math.floor(number);
        }
        if (precision === UptimePrecision.ONE_DECIMAL) {
            return Math.floor(number * 10) / 10;
        }
        if (precision === UptimePrecision.TWO_DECIMAL) {
            return Math.floor(number * 100) / 100;
        }
        if (precision === UptimePrecision.THREE_DECIMAL) {
            return Math.floor(number * 1000) / 1000;
        }
        return number;
    }
    static calculateUptimePercentage(monitorStatusTimelines, precision, downtimeMonitorStatuses) {
        // calculate percentage.
        const { totalDowntimeInSeconds, totalSecondsInTimePeriod } = this.getTotalDowntimeInSeconds(monitorStatusTimelines, downtimeMonitorStatuses);
        if (totalSecondsInTimePeriod === 0) {
            return 100;
        }
        if (totalDowntimeInSeconds === 0) {
            return 100;
        }
        const percentage = ((totalSecondsInTimePeriod - totalDowntimeInSeconds) /
            totalSecondsInTimePeriod) *
            100;
        return this.roundToPrecision({
            number: percentage,
            precision,
        });
    }
    static calculateAvgUptimePercentage(data) {
        // calculate percentage.
        const { uptimePercentages, precision } = data;
        if (uptimePercentages.length === 0) {
            return 100;
        }
        let totalUptimePercentage = 0;
        for (const uptimePercentage of uptimePercentages) {
            totalUptimePercentage += uptimePercentage;
        }
        const percentage = totalUptimePercentage / uptimePercentages.length;
        return this.roundToPrecision({
            number: percentage,
            precision,
        });
    }
}
//# sourceMappingURL=UptimeUtil.js.map