"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.run = run;
const fs_1 = require("fs");
const util_1 = require("util");
const utils_1 = require("../utils");
async function run(args) {
    const options = {
        help: {
            type: 'boolean',
            short: 'h',
        },
        update: {
            type: 'boolean',
            short: 'u',
            description: 'Update the contents of an existing track, matched based on trackId',
        },
        target: {
            type: 'string',
            description: 'Path to config file in JB2 installation directory to write out to',
        },
        out: {
            type: 'string',
            description: 'Synonym for target',
        },
    };
    const { values: flags, positionals } = (0, util_1.parseArgs)({
        args,
        options,
        allowPositionals: true,
    });
    const description = 'Add a track configuration directly from a JSON hunk to the JBrowse 2 configuration';
    const examples = [
        '$ jbrowse add-track-json track.json',
        '$ jbrowse add-track-json track.json --update',
    ];
    if (flags.help) {
        (0, utils_1.printHelp)({
            description,
            examples,
            usage: 'jbrowse add-track-json <track> [options]',
            options,
        });
        return;
    }
    const track = positionals[0];
    if (!track) {
        console.error('Error: Missing required argument: track');
        console.error('Usage: jbrowse add-track-json <track> [options]');
        process.exit(1);
    }
    const output = flags.target || flags.out || '.';
    const isDir = (await fs_1.promises.lstat(output)).isDirectory();
    const target = isDir ? `${output}/config.json` : output;
    (0, utils_1.debug)(`Sequence location is: ${track}`);
    const { update } = flags;
    const config = await (0, utils_1.readJsonFile)(target);
    (0, utils_1.debug)(`Found existing config file ${target}`);
    const trackConfig = await (0, utils_1.readInlineOrFileJson)(track);
    if (!config.tracks) {
        config.tracks = [];
    }
    const idx = config.tracks.findIndex(({ trackId }) => trackId === trackConfig.trackId);
    if (idx !== -1) {
        const existing = config.tracks[idx]?.name;
        (0, utils_1.debug)(`Found existing track ${existing} in configuration`);
        if (update) {
            (0, utils_1.debug)(`Overwriting track ${existing} in configuration`);
            config.tracks[idx] = trackConfig;
        }
        else {
            throw new Error(`Cannot add track ${trackConfig.name}, a track with that trackId already exists: ${existing}`);
        }
    }
    else {
        config.tracks.push(trackConfig);
    }
    (0, utils_1.debug)(`Writing configuration to file ${target}`);
    await (0, utils_1.writeJsonFile)(target, config);
    console.log(`${idx !== -1 ? 'Overwrote' : 'Added'} track "${trackConfig.name}" ${idx !== -1 ? 'in' : 'to'} ${target}`);
}
