"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const chalk_1 = __importDefault(require("chalk"));
const iterators_1 = require("@thi.ng/iterators");
const config_1 = require("../../../config");
const client_1 = require("../../../client");
const command_helpers_1 = require("../../../command-helpers");
const rules_1 = require("../../../rules");
const HELP = `
${chalk_1.default.bold('graph indexer rules set')} [options] global          <key1> <value1> ...
${chalk_1.default.bold('graph indexer rules set')} [options] <deployment-id> <key1> <value1> ...

${chalk_1.default.dim('Options:')}

  -h, --help                    Show usage information
  -o, --output table|json|yaml  Choose the output format: table (default), JSON, or YAML
`;
module.exports = {
    name: 'set',
    alias: [],
    description: 'Set one or more indexing rules',
    run: (toolbox) => __awaiter(void 0, void 0, void 0, function* () {
        const { print, parameters } = toolbox;
        const { h, help, o, output } = parameters.options;
        const [deployment, ...keyValues] = command_helpers_1.fixParameters(parameters, { h, help }) || [];
        const outputFormat = o || output || 'table';
        if (help || h) {
            print.info(HELP);
            return;
        }
        if (!['json', 'yaml', 'table'].includes(outputFormat)) {
            print.error(`Invalid output format "${outputFormat}"`);
            process.exitCode = 1;
            return;
        }
        try {
            command_helpers_1.validateDeploymentID(deployment, { all: false, global: true });
        }
        catch (error) {
            print.error(error.toString());
            process.exitCode = 1;
            return;
        }
        const config = config_1.loadValidatedConfig();
        //// Parse key/value pairs
        // 1. Convert all `null` strings to real nulls, and other values
        //    to regular JS strings (which for some reason they are not...)
        const kvs = keyValues.map(param => (param === 'null' ? null : param.toString()));
        // 2. Check that all key/value pairs are complete and
        // there's no value missing at the end
        if (kvs.length % 2 !== 0) {
            print.error(`An uneven number of key/value pairs was passed in: ${kvs.join(' ')}`);
            process.exitCode = 1;
            return;
        }
        // Turn the array into an object, add a `deployment` key
        const inputRule = rules_1.parseIndexingRule(Object.assign(Object.assign({}, Object.fromEntries([...iterators_1.partition(2, 2, kvs)])), { deployment }));
        if (inputRule.parallelAllocations && inputRule.parallelAllocations >= 2) {
            throw Error('Parallel allocations are soon to be fully deprecated. Please set parallel allocations to 1 for all your indexing rules');
        }
        // Update the indexing rule according to the key/value pairs
        try {
            const client = yield client_1.createIndexerManagementClient({ url: config.api });
            const rule = yield rules_1.setIndexingRule(client, inputRule);
            rules_1.printIndexingRules(print, outputFormat, rules_1.parseDeploymentID(deployment), rule, []);
        }
        catch (error) {
            print.error(error.toString());
        }
    }),
};
