"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',
        },
        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 = 'Remove a track configuration from a JBrowse 2 configuration. Be aware that this can cause crashes in saved sessions that refer to this track!';
    const examples = ['$ jbrowse remove-track trackId'];
    if (flags.help) {
        (0, utils_1.printHelp)({
            description,
            examples,
            usage: 'jbrowse remove-track <trackId> [options]',
            options,
        });
        return;
    }
    const trackId = positionals[0];
    if (!trackId) {
        console.error('Error: Missing required argument: trackId');
        console.error('Usage: jbrowse remove-track <trackId> [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;
    const config = await (0, utils_1.readJsonFile)(target);
    const originalLength = config.tracks?.length || 0;
    config.tracks = config.tracks?.filter(({ trackId: id }) => id !== trackId);
    const newLength = config.tracks?.length || 0;
    if (originalLength === newLength) {
        console.log(`No track found with trackId: ${trackId}`);
    }
    else {
        await (0, utils_1.writeJsonFile)(target, config);
        console.log(`Removed track with trackId: ${trackId} from ${target}`);
    }
}
