"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const command_1 = require("@oclif/command");
const fs_1 = require("fs");
const base_1 = __importDefault(require("../base"));
class AddTrackJson extends base_1.default {
    async run() {
        const { args, flags: runFlags } = this.parse(AddTrackJson);
        const output = runFlags.target || runFlags.out || '.';
        const isDir = (await fs_1.promises.lstat(output)).isDirectory();
        this.target = isDir ? `${output}/config.json` : output;
        const { track: inputtedTrack } = args;
        this.debug(`Sequence location is: ${inputtedTrack}`);
        const { update } = runFlags;
        const config = await this.readJsonFile(this.target);
        this.debug(`Found existing config file ${this.target}`);
        const track = await this.readInlineOrFileJson(inputtedTrack);
        if (!config.tracks) {
            config.tracks = [];
        }
        const idx = config.tracks.findIndex(({ trackId }) => trackId === track.trackId);
        if (idx !== -1) {
            const existing = config.tracks[idx].name;
            this.debug(`Found existing track ${existing} in configuration`);
            if (update) {
                this.debug(`Overwriting track ${existing} in configuration`);
                config.tracks[idx] = track;
            }
            else {
                this.error(`Cannot add track ${track.name}, a track with that trackId already exists: ${existing}`, { exit: 160 });
            }
        }
        else {
            config.tracks.push(track);
        }
        this.debug(`Writing configuration to file ${this.target}`);
        await this.writeJsonFile(this.target, config);
        this.log(`${idx !== -1 ? 'Overwrote' : 'Added'} assembly "${track.name}" ${idx !== -1 ? 'in' : 'to'} ${this.target}`);
    }
}
exports.default = AddTrackJson;
AddTrackJson.description = 'Add a track configuration directly from a JSON hunk to the JBrowse 2 configuration';
AddTrackJson.examples = [
    '$ jbrowse add-track-json track.json',
    '$ jbrowse add-track-json track.json --update',
];
AddTrackJson.args = [
    {
        name: 'track',
        required: true,
        description: `track JSON file or command line arg blob`,
    },
];
AddTrackJson.flags = {
    update: command_1.flags.boolean({
        char: 'u',
        description: `update the contents of an existing track, matched based on trackId`,
    }),
    target: command_1.flags.string({
        description: 'path to config file in JB2 installation directory to write out to.\nCreates ./config.json if nonexistent',
    }),
    out: command_1.flags.string({
        description: 'synonym for target',
    }),
};
