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/OnCallDutyPolicyScheduleLayerUser";
import CaptureSpan from "../Utils/Telemetry/CaptureSpan";
import OnCallDutyPolicyScheduleService from "./OnCallDutyPolicyScheduleService";
export class Service extends DatabaseService {
    constructor() {
        super(Model);
    }
    async onBeforeCreate(createBy) {
        var _a;
        if (!createBy.data.onCallDutyPolicyScheduleLayerId) {
            throw new BadDataException("onCallDutyPolicyScheduleLayerId is required");
        }
        const userId = createBy.data.userId || ((_a = createBy.data.user) === null || _a === void 0 ? void 0 : _a.id);
        if (!userId) {
            throw new BadDataException("userId is required");
        }
        if (!createBy.data.order) {
            // count number of users in this layer.
            const count = await this.countBy({
                query: {
                    onCallDutyPolicyScheduleLayerId: createBy.data.onCallDutyPolicyScheduleLayerId,
                },
                props: {
                    isRoot: true,
                },
            });
            createBy.data.order = count.toNumber() + 1;
        }
        await this.rearrangeOrder(createBy.data.order, createBy.data.onCallDutyPolicyScheduleLayerId, true);
        return {
            createBy,
            carryForward: null,
        };
    }
    async onDeleteSuccess(onDelete, _itemIdsBeforeDelete) {
        const deleteBy = onDelete.deleteBy;
        const resource = onDelete.carryForward;
        if (!deleteBy.props.isRoot && resource) {
            if (resource &&
                resource.order &&
                resource.onCallDutyPolicyScheduleLayerId) {
                await this.rearrangeOrder(resource.order, resource.onCallDutyPolicyScheduleLayerId, false);
                if (resource.onCallDutyPolicyScheduleId) {
                    await OnCallDutyPolicyScheduleService.refreshCurrentUserIdAndHandoffTimeInSchedule(resource.onCallDutyPolicyScheduleId);
                }
            }
        }
        return {
            deleteBy: deleteBy,
            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,
                    onCallDutyPolicyScheduleLayerId: true,
                    onCallDutyPolicyScheduleId: true,
                },
            });
        }
        return {
            deleteBy,
            carryForward: resource,
        };
    }
    async onCreateSuccess(_onCreate, createdItem) {
        const resource = await this.findOneById({
            id: createdItem.id,
            select: {
                onCallDutyPolicyScheduleId: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (!resource || !resource.onCallDutyPolicyScheduleId) {
            return createdItem;
        }
        await OnCallDutyPolicyScheduleService.refreshCurrentUserIdAndHandoffTimeInSchedule(resource.onCallDutyPolicyScheduleId);
        return createdItem;
    }
    async onUpdateSuccess(_onUpdate, updatedItemIds) {
        for (const item of updatedItemIds) {
            const resource = await this.findOneById({
                id: item,
                select: {
                    onCallDutyPolicyScheduleId: true,
                },
                props: {
                    isRoot: true,
                },
            });
            if (!resource || !resource.onCallDutyPolicyScheduleId) {
                continue;
            }
            await OnCallDutyPolicyScheduleService.refreshCurrentUserIdAndHandoffTimeInSchedule(resource.onCallDutyPolicyScheduleId);
        }
        return {
            updateBy: _onUpdate.updateBy,
            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,
                    onCallDutyPolicyScheduleLayerId: 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: {
                    onCallDutyPolicyScheduleLayerId: resource === null || resource === void 0 ? void 0 : resource.onCallDutyPolicyScheduleLayerId,
                },
                limit: LIMIT_MAX,
                skip: 0,
                props: {
                    isRoot: true,
                },
                select: {
                    order: true,
                    onCallDutyPolicyScheduleLayerId: 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, onCallDutyPolicyScheduleLayerId, increaseOrder = true) {
        // get status page resource with this order.
        const resources = await this.findBy({
            query: {
                order: QueryHelper.greaterThanEqualTo(currentOrder),
                onCallDutyPolicyScheduleLayerId: onCallDutyPolicyScheduleLayerId,
            },
            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, "onBeforeCreate", 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, "onBeforeDelete", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], Service.prototype, "onBeforeUpdate", null);
export default new Service();
//# sourceMappingURL=OnCallDutyPolicyScheduleLayerUserService.js.map