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 WorkflowService from "../../../Services/WorkflowService";
import QueryHelper from "../../Database/QueryHelper";
import TriggerCode from "../TriggerCode";
import LIMIT_MAX from "../../../../Types/Database/LimitMax";
import BadDataException from "../../../../Types/Exception/BadDataException";
import ObjectID from "../../../../Types/ObjectID";
import ComponentID from "../../../../Types/Workflow/ComponentID";
import ScheduleComponents from "../../../../Types/Workflow/Components/Schedule";
import CaptureSpan from "../../../Utils/Telemetry/CaptureSpan";
export default class WebhookTrigger extends TriggerCode {
    constructor() {
        const component = ScheduleComponents.find((i) => {
            return i.id === ComponentID.Schedule;
        });
        if (!component) {
            throw new BadDataException("Trigger not found.");
        }
        super();
        this.setMetadata(component);
    }
    async init(props) {
        const workflows = await WorkflowService.findBy({
            query: {
                triggerId: ComponentID.Schedule,
                triggerArguments: QueryHelper.notNull(),
            },
            select: {
                _id: true,
                triggerArguments: true,
                isEnabled: true,
            },
            props: {
                isRoot: true,
            },
            limit: LIMIT_MAX,
            skip: 0,
        });
        // query all workflows.
        for (const workflow of workflows) {
            const executeWorkflow = {
                workflowId: new ObjectID(workflow._id),
                returnValues: {},
            };
            if (workflow.triggerArguments &&
                workflow.triggerArguments["schedule"] &&
                workflow.isEnabled) {
                await props.scheduleWorkflow(executeWorkflow, workflow.triggerArguments["schedule"]);
            }
            if (!workflow.isEnabled) {
                await props.removeWorkflow(workflow.id);
            }
        }
    }
    async run(args, options) {
        const successPort = this.getMetadata().outPorts.find((p) => {
            return p.id === "execute";
        });
        if (!successPort) {
            throw options.onError(new BadDataException("Execute port not found"));
        }
        return {
            returnValues: Object.assign({}, args),
            executePort: successPort,
        };
    }
    async update(props) {
        const workflow = await WorkflowService.findOneBy({
            query: {
                triggerId: ComponentID.Schedule,
                _id: props.workflowId.toString(),
                triggerArguments: QueryHelper.notNull(),
            },
            select: {
                _id: true,
                triggerArguments: true,
                isEnabled: true,
            },
            props: {
                isRoot: true,
            },
        });
        if (!workflow) {
            return;
        }
        if (!this.scheduleWorkflow) {
            return;
        }
        const executeWorkflow = {
            workflowId: new ObjectID(workflow._id),
            returnValues: {},
        };
        if (workflow.triggerArguments &&
            workflow.triggerArguments["schedule"] &&
            workflow.isEnabled) {
            await this.scheduleWorkflow(executeWorkflow, workflow.triggerArguments["schedule"]);
        }
        if (!this.removeWorkflow) {
            return;
        }
        if (!workflow.isEnabled) {
            await this.removeWorkflow(workflow.id);
        }
    }
}
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], WebhookTrigger.prototype, "init", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object, Object]),
    __metadata("design:returntype", Promise)
], WebhookTrigger.prototype, "run", null);
__decorate([
    CaptureSpan(),
    __metadata("design:type", Function),
    __metadata("design:paramtypes", [Object]),
    __metadata("design:returntype", Promise)
], WebhookTrigger.prototype, "update", null);
//# sourceMappingURL=Schedule.js.map