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 QueryHelper from "../Types/Database/QueryHelper";
import DatabaseService from "./DatabaseService";
import MonitorGroupResourceService from "./MonitorGroupResourceService";
import MonitorStatusService from "./MonitorStatusService";
import MonitorStatusTimelineService from "./MonitorStatusTimelineService";
import SortOrder from "../../Types/BaseDatabase/SortOrder";
import LIMIT_MAX, { LIMIT_PER_PROJECT } from "../../Types/Database/LimitMax";
import BadDataException from "../../Types/Exception/BadDataException";
import ObjectID from "../../Types/ObjectID";
import MonitorGroup from "../../Models/DatabaseModels/MonitorGroup";
import StatusPageResourceService from "./StatusPageResourceService";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
export class Service extends DatabaseService {
    constructor() {
        super(MonitorGroup);
    }
    async onBeforeDelete(deleteBy) {
        if (deleteBy.query._id) {
            // delete all the status page resource for this monitor.
            await StatusPageResourceService.deleteBy({
                query: {
                    monitorGroupId: new ObjectID(deleteBy.query._id),
                },
                limit: LIMIT_MAX,
                skip: 0,
                props: {
                    isRoot: true,
                },
            });
        }
        return { deleteBy, carryForward: null };
    }
    async getStatusTimeline(monitorGroupId, startDate, endDate, props) {
        const monitorGroup = await this.findOneById({
            id: monitorGroupId,
            select: {
                _id: true,
                projectId: true,
            },
            props: props,
        });
        if (!monitorGroup) {
            throw new BadDataException("Monitor group not found.");
        }
        const monitorGroupResources = await MonitorGroupResourceService.findBy({
            query: {
                monitorGroupId: monitorGroup.id,
            },
            limit: LIMIT_PER_PROJECT,
            skip: 0,
            select: {
                monitorId: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (monitorGroupResources.length === 0) {
            return [];
        }
        const monitorStatusTimelines = await MonitorStatusTimelineService.findBy({
            query: {
                monitorId: QueryHelper.any(monitorGroupResources.map((monitorGroupResource) => {
                    return monitorGroupResource.monitorId;
                })),
                createdAt: QueryHelper.inBetween(startDate, endDate),
            },
            select: {
                createdAt: true,
                monitorId: true,
                startsAt: true,
                endsAt: true,
                monitorStatus: {
                    name: true,
                    color: true,
                    isOperationalState: true,
                    priority: true,
                },
            },
            sort: {
                createdAt: SortOrder.Ascending,
            },
            skip: 0,
            limit: LIMIT_MAX, // This can be optimized.
            props: {
                isRoot: true,
            },
        });
        return monitorStatusTimelines;
    }
    async getCurrentStatus(monitorGroupId, props) {
        // get group id.
        const monitorGroup = await this.findOneById({
            id: monitorGroupId,
            select: {
                _id: true,
                projectId: true,
            },
            props: props,
        });
        if (!monitorGroup) {
            throw new BadDataException("Monitor group not found.");
        }
        // now get all the monitors in this group with current status.
        const monitorGroupResources = await MonitorGroupResourceService.findBy({
            query: {
                monitorGroupId: monitorGroup.id,
            },
            limit: LIMIT_PER_PROJECT,
            skip: 0,
            select: {
                monitor: {
                    currentMonitorStatusId: true,
                },
            },
            props: {
                isRoot: true,
            },
        });
        const monitorStatuses = await MonitorStatusService.findBy({
            query: {
                projectId: monitorGroup.projectId,
            },
            limit: LIMIT_PER_PROJECT,
            skip: 0,
            select: {
                name: true,
                color: true,
                priority: true,
                isOperationalState: true,
            },
            props: {
                isRoot: true,
            },
        });
        let currentStatus = monitorStatuses.find((monitorStatus) => {
            return monitorStatus.isOperationalState;
        });
        if (!currentStatus) {
            throw new BadDataException("Operational state not found.");
        }
        for (const monitorGroupResource of monitorGroupResources) {
            if (!monitorGroupResource.monitor) {
                continue;
            }
            const monitorStatus = monitorStatuses.find((monitorStatus) => {
                var _a, _b;
                return (((_a = monitorStatus.id) === null || _a === void 0 ? void 0 : _a.toString()) ===
                    ((_b = monitorGroupResource.monitor.currentMonitorStatusId) === null || _b === void 0 ? void 0 : _b.toString()));
            });
            if (monitorStatus && currentStatus.priority < monitorStatus.priority) {
                currentStatus = monitorStatus;
            }
        }
        return currentStatus;
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeDelete", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID,
        Date,
        Date, Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "getStatusTimeline", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [ObjectID, Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "getCurrentStatus", null);
export default new Service();
//# sourceMappingURL=MonitorGroupService.js.map