"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseWorkflowRecurringAutoStopOption = parseWorkflowRecurringAutoStopOption;
const workflow_option_parse_shared_1 = require("./workflow-option-parse-shared");
function parseWorkflowRecurringAutoStopOption(tokens, index, optionSpec, existingAutoStop, inlineTrailingText) {
    if (optionSpec.target === "off") {
        const conflict = (0, workflow_option_parse_shared_1.rejectExistingWorkflowCommandOptionValues)([existingAutoStop], "conflicting-schedule-options", inlineTrailingText);
        if (conflict !== undefined) {
            return conflict;
        }
        return (0, workflow_option_parse_shared_1.buildWorkflowCommandOptionFlagUpdateResult)({ recurringAutoStop: { mode: "off" } }, inlineTrailingText);
    }
    const offConflict = (0, workflow_option_parse_shared_1.rejectExistingWorkflowCommandOptionValues)([existingAutoStop?.mode === "off" ? existingAutoStop : undefined], "conflicting-schedule-options", inlineTrailingText);
    if (offConflict !== undefined) {
        return offConflict;
    }
    const previous = existingAutoStop?.mode === "update" ? existingAutoStop : { mode: "update" };
    if (optionSpec.target === "stopAt" || optionSpec.target === "stopAfter") {
        const conflict = (0, workflow_option_parse_shared_1.rejectExistingWorkflowCommandOptionValues)([previous.stopAt, previous.stopAfter], "conflicting-schedule-options", inlineTrailingText);
        if (conflict !== undefined) {
            return conflict;
        }
    }
    if (optionSpec.target === "stopAfterRuns") {
        const conflict = (0, workflow_option_parse_shared_1.rejectExistingWorkflowCommandOptionValues)([previous.stopAfterRuns], "duplicate-option", inlineTrailingText);
        if (conflict !== undefined) {
            return conflict;
        }
    }
    return (0, workflow_option_parse_shared_1.parseRequiredWorkflowCommandOptionUpdate)(tokens, index, inlineTrailingText, (value) => {
        const recurringAutoStop = parseRecurringAutoStopValue(optionSpec, value, previous);
        return recurringAutoStop === null ? null : { recurringAutoStop };
    });
}
function parseRecurringAutoStopValue(optionSpec, value, previous) {
    if (optionSpec.target === "stopAt") {
        const stopAt = (0, workflow_option_parse_shared_1.parseWorkflowRunAtOrAfterOptionValue)("run_at", value);
        return stopAt === null ? null : { ...previous, stopAt: stopAt.value };
    }
    if (optionSpec.target === "stopAfter") {
        const stopAfter = (0, workflow_option_parse_shared_1.parseWorkflowRunAtOrAfterOptionValue)("run_after", value);
        return stopAfter === null
            ? null
            : { ...previous, stopAfter: stopAfter.value };
    }
    const stopAfterRuns = Number(value);
    return Number.isSafeInteger(stopAfterRuns) && stopAfterRuns > 0
        ? { ...previous, stopAfterRuns }
        : null;
}
