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 SortOrder from "../../Types/BaseDatabase/SortOrder";
import LIMIT_MAX, { LIMIT_PER_PROJECT } from "../../Types/Database/LimitMax";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import BadDataException from "../../Types/Exception/BadDataException";
import ObjectID from "../../Types/ObjectID";
import Model from "../../Models/DatabaseModels/StatusPageResource";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async findByMonitors(data) {
        let resolvedMonitorIds;
        if (data.monitorIds && data.monitorIds.length > 0) {
            resolvedMonitorIds = data.monitorIds;
        }
        else if (data.monitors && data.monitors.length > 0) {
            resolvedMonitorIds = data.monitors
                .filter((m) => {
                return m._id;
            })
                .map((m) => {
                return new ObjectID(m._id);
            });
        }
        else {
            return [];
        }
        if (resolvedMonitorIds.length === 0) {
            return [];
        }
        // Find status page resources directly linked to monitors
        const statusPageResources = await this.findBy({
            query: {
                monitorId: QueryHelper.any(resolvedMonitorIds),
            },
            props: {
                isRoot: true,
                ignoreHooks: true,
            },
            skip: 0,
            limit: LIMIT_PER_PROJECT,
            select: data.select,
        });
        // Find monitor groups that contain the affected monitors
        const monitorGroupResources = await MonitorGroupResourceService.findBy({
            query: {
                monitorId: QueryHelper.any(resolvedMonitorIds),
            },
            props: {
                isRoot: true,
                ignoreHooks: true,
            },
            select: {
                monitorGroupId: true,
            },
            skip: 0,
            limit: LIMIT_PER_PROJECT,
        });
        const monitorGroupIds = monitorGroupResources
            .map((r) => {
            return r.monitorGroupId;
        })
            .filter((id) => {
            return Boolean(id);
        });
        if (monitorGroupIds.length > 0) {
            const groupStatusPageResources = await this.findBy({
                query: {
                    monitorGroupId: QueryHelper.any(monitorGroupIds),
                },
                props: {
                    isRoot: true,
                    ignoreHooks: true,
                },
                skip: 0,
                limit: LIMIT_PER_PROJECT,
                select: data.select,
            });
            // Merge and deduplicate
            for (const resource of groupStatusPageResources) {
                const alreadyExists = statusPageResources.some((r) => {
                    return r._id === resource._id;
                });
                if (!alreadyExists) {
                    statusPageResources.push(resource);
                }
            }
        }
        return statusPageResources;
    }
    async onBeforeCreate(createBy) {
        if (!createBy.data.statusPageId) {
            throw new BadDataException("Status Page Resource statusPageId is required");
        }
        if (!createBy.data.order) {
            const query = {
                statusPageId: createBy.data.statusPageId,
                statusPageGroupId: createBy.data.statusPageGroupId || QueryHelper.isNull(),
            };
            if (createBy.data.statusPageGroupId) {
                query["statusPageGroupId"] = createBy.data.statusPageGroupId;
            }
            else {
                query["statusPageGroupId"] = QueryHelper.isNull();
            }
            const count = await this.countBy({
                query: query,
                props: {
                    isRoot: true,
                },
            });
            createBy.data.order = count.toNumber() + 1;
        }
        await this.rearrangeOrder(createBy.data.order, createBy.data.statusPageId, createBy.data.statusPageGroupId || null, true);
        return {
            createBy: createBy,
            carryForward: null,
        };
    }
    async onBeforeDelete(deleteBy) {
        if (!deleteBy.query._id && !deleteBy.props.isRoot) {
            throw new BadDataException("_id should be present when deleting status page resource. Please try the delete with objectId");
        }
        let resource = null;
        if (!deleteBy.props.isRoot) {
            resource = await this.findOneBy({
                query: deleteBy.query,
                props: {
                    isRoot: true,
                },
                select: {
                    order: true,
                    statusPageId: true,
                    statusPageGroupId: true,
                },
            });
        }
        return {
            deleteBy,
            carryForward: resource,
        };
    }
    async onDeleteSuccess(onDelete, _itemIdsBeforeDelete) {
        const deleteBy = onDelete.deleteBy;
        const resource = onDelete.carryForward;
        if (!deleteBy.props.isRoot && resource) {
            if (resource && resource.order && resource.statusPageId) {
                await this.rearrangeOrder(resource.order, resource.statusPageId, resource.statusPageGroupId || null, false);
            }
        }
        return {
            deleteBy: deleteBy,
            carryForward: null,
        };
    }
    async onBeforeUpdate(updateBy) {
        if (updateBy.data.order && !updateBy.props.isRoot && updateBy.query._id) {
            const resource = await this.findOneBy({
                query: {
                    _id: updateBy.query._id,
                },
                props: {
                    isRoot: true,
                },
                select: {
                    order: true,
                    statusPageId: true,
                    statusPageGroupId: true,
                    _id: true,
                },
            });
            const currentOrder = resource === null || resource === void 0 ? void 0 : resource.order;
            const newOrder = updateBy.data.order;
            const resources = await this.findBy({
                query: {
                    statusPageId: resource === null || resource === void 0 ? void 0 : resource.statusPageId,
                    statusPageGroupId: (resource === null || resource === void 0 ? void 0 : resource.statusPageGroupId) || QueryHelper.isNull(),
                },
                limit: LIMIT_MAX,
                skip: 0,
                props: {
                    isRoot: true,
                },
                select: {
                    order: true,
                    statusPageId: true,
                    statusPageGroupId: true,
                    _id: true,
                },
            });
            if (currentOrder > newOrder) {
                // moving up.
                for (const resource of resources) {
                    if (resource.order >= newOrder && resource.order < currentOrder) {
                        // increment order.
                        await this.updateOneBy({
                            query: {
                                _id: resource._id,
                            },
                            data: {
                                order: resource.order + 1,
                            },
                            props: {
                                isRoot: true,
                            },
                        });
                    }
                }
            }
            if (newOrder > currentOrder) {
                // moving down.
                for (const resource of resources) {
                    if (resource.order <= newOrder) {
                        // increment order.
                        await this.updateOneBy({
                            query: {
                                _id: resource._id,
                            },
                            data: {
                                order: resource.order - 1,
                            },
                            props: {
                                isRoot: true,
                            },
                        });
                    }
                }
            }
        }
        return { updateBy, carryForward: null };
    }
    async rearrangeOrder(currentOrder, statusPageId, statusPageGroupId, increaseOrder = true) {
        // get status page resource with this order.
        const resources = await this.findBy({
            query: {
                order: QueryHelper.greaterThanEqualTo(currentOrder),
                statusPageId: statusPageId,
                statusPageGroupId: statusPageGroupId
                    ? statusPageGroupId
                    : QueryHelper.isNull(),
            },
            limit: LIMIT_MAX,
            skip: 0,
            props: {
                isRoot: true,
            },
            select: {
                _id: true,
                order: true,
            },
            sort: {
                order: SortOrder.Ascending,
            },
        });
        let newOrder = currentOrder;
        for (const resource of resources) {
            if (increaseOrder) {
                newOrder = resource.order + 1;
            }
            else {
                newOrder = resource.order - 1;
            }
            await this.updateOneBy({
                query: {
                    _id: resource._id,
                },
                data: {
                    order: newOrder,
                },
                props: {
                    isRoot: true,
                },
            });
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "findByMonitors", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeCreate", null);
__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", [Object, Array]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onDeleteSuccess", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeUpdate", null);
export default new Service();
//# sourceMappingURL=StatusPageResourceService.js.map