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 SortOrder from "../../Types/BaseDatabase/SortOrder";
import LIMIT_MAX from "../../Types/Database/LimitMax";
import BadDataException from "../../Types/Exception/BadDataException";
import Model from "../../Models/DatabaseModels/MonitorStatus";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onBeforeCreate(createBy) {
        if (!createBy.data.priority) {
            throw new BadDataException("Monitor Status priority is required");
        }
        if (!createBy.data.projectId) {
            throw new BadDataException("Monitor Status projectId is required");
        }
        await this.rearrangePriority(createBy.data.priority, createBy.data.projectId, 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 Monitor Status. Please try the delete with objectId");
        }
        let monitorStatus = null;
        if (!deleteBy.props.isRoot) {
            monitorStatus = await this.findOneBy({
                query: deleteBy.query,
                props: {
                    isRoot: true,
                },
                select: {
                    priority: true,
                    projectId: true,
                },
            });
        }
        return {
            deleteBy,
            carryForward: monitorStatus,
        };
    }
    async onDeleteSuccess(onDelete, _itemIdsBeforeDelete) {
        const deleteBy = onDelete.deleteBy;
        const monitorStatus = onDelete.carryForward;
        if (!deleteBy.props.isRoot && monitorStatus) {
            if (monitorStatus && monitorStatus.priority && monitorStatus.projectId) {
                await this.rearrangePriority(monitorStatus.priority, monitorStatus.projectId, false);
            }
        }
        return {
            deleteBy: deleteBy,
            carryForward: null,
        };
    }
    async onBeforeUpdate(updateBy) {
        if (updateBy.data.priority && !updateBy.props.isRoot) {
            throw new BadDataException("Monitor Status priority should not be updated. Delete this monitor status and create a new state with the right priority.");
        }
        return { updateBy, carryForward: null };
    }
    async rearrangePriority(currentPriority, projectId, increasePriority = true) {
        // get monitor status with this priority.
        const monitorStatuses = await this.findBy({
            query: {
                priority: QueryHelper.greaterThanEqualTo(currentPriority),
                projectId: projectId,
            },
            limit: LIMIT_MAX,
            skip: 0,
            props: {
                isRoot: true,
            },
            select: {
                _id: true,
                priority: true,
            },
            sort: {
                priority: SortOrder.Ascending,
            },
        });
        let newPriority = currentPriority;
        for (const monitorStatus of monitorStatuses) {
            if (increasePriority) {
                newPriority = monitorStatus.priority + 1;
            }
            else {
                newPriority = monitorStatus.priority - 1;
            }
            await this.updateOneBy({
                query: {
                    _id: monitorStatus._id,
                },
                data: {
                    priority: newPriority,
                },
                props: {
                    isRoot: true,
                },
            });
        }
    }
}
__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=MonitorStatusService.js.map