"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseServiceArgs = parseServiceArgs;
const service_1 = require("../../commands/service");
const catalog_1 = require("../../i18n/catalog");
const shared_1 = require("./shared");
function parseServiceArgs(args, options) {
    const locale = options?.locale ?? catalog_1.DEFAULT_APP_LOCALE;
    const [action, ...rest] = args;
    if (!action) {
        throw new Error((0, catalog_1.translate)(locale, "cli.parser.service.usage", {
            usage: service_1.SERVICE_COMMAND_USAGE,
        }));
    }
    if (action === "log") {
        return parseServiceLogArgs(rest, locale);
    }
    const force = parseForceOption(action, rest, locale);
    if (action === "disable" || action === "restart") {
        return force ? { action, force } : { action };
    }
    if (options?.allowInternal && (0, service_1.isServiceCommandAction)(action)) {
        return { action };
    }
    if ((0, service_1.isPublicServiceCommandAction)(action)) {
        return { action };
    }
    throw new Error((0, catalog_1.translate)(locale, "cli.parser.service.unknownCommand", { action }));
}
function parseForceOption(action, args, locale) {
    if (args.length === 0) {
        return false;
    }
    if ((action === "disable" || action === "restart") &&
        args.length === 1 &&
        args[0] === "--force") {
        return true;
    }
    throw new Error((0, catalog_1.translate)(locale, "cli.parser.service.unknownArgument", {
        token: args[0] ?? "",
    }));
}
function parseServiceLogArgs(args, locale) {
    const [action, ...rest] = args;
    if (!action) {
        throw new Error((0, catalog_1.translate)(locale, "cli.parser.service.log.usage"));
    }
    if (action !== "show") {
        throw new Error((0, catalog_1.translate)(locale, "cli.parser.service.log.unknownCommand", { action }));
    }
    const values = {};
    for (let index = 0; index < rest.length; index += 1) {
        const token = rest[index];
        const value = rest[index + 1];
        switch (token) {
            case "--tail":
                values.tail = (0, shared_1.parseRequiredOptionValue)(token, value, locale, (optionValue) => (0, shared_1.parsePositiveIntegerArg)("--tail", optionValue, locale));
                index += 1;
                break;
            default:
                throw new Error((0, catalog_1.translate)(locale, "cli.parser.service.log.show.unknownOption", {
                    token: token ?? "",
                }));
        }
    }
    return values.tail === undefined
        ? {
            action: "log-show",
        }
        : {
            action: "log-show",
            tail: values.tail,
        };
}
