"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.run = run;
const fs_1 = __importDefault(require("fs"));
const util_1 = require("util");
const json_parse_better_errors_1 = __importDefault(require("json-parse-better-errors"));
const utils_1 = require("../utils");
const fsPromises = fs_1.default.promises;
const description = 'Set a default session with views and tracks';
const examples = [
    '# set default session for the config.json in your current directory',
    '$ jbrowse set-default-session --session /path/to/default/session.json',
    '',
    '# make session.json the defaultSession on the specified target config.json file',
    '$ jbrowse set-default-session --target /path/to/jb2/installation/config.json --session session.json',
    '',
    '# print current default session',
    '$ jbrowse set-default-session --currentSession # Prints out current default session',
];
const options = {
    session: {
        type: 'string',
        short: 's',
        description: 'set path to a file containing session in json format (required, unless using delete/currentSession flags)',
    },
    name: {
        type: 'string',
        short: 'n',
        description: 'Give a name for the default session',
        default: 'New Default Session',
    },
    currentSession: {
        type: 'boolean',
        short: 'c',
        description: 'List out the current default session',
    },
    target: {
        type: 'string',
        description: 'path to config file in JB2 installation directory to write out to',
    },
    out: { type: 'string', description: 'synonym for target' },
    delete: {
        type: 'boolean',
        description: 'Delete any existing default session.',
    },
    help: { type: 'boolean', short: 'h', description: 'Show help' },
};
async function run(args) {
    const { values: runFlags } = (0, util_1.parseArgs)({ options, args });
    if (runFlags.help) {
        (0, utils_1.printHelp)({
            description,
            examples,
            usage: 'jbrowse add-track <track> [options]',
            options,
        });
        return;
    }
    const { session, currentSession, delete: deleteDefaultSession } = runFlags;
    const output = runFlags.target || runFlags.out || '.';
    const isDir = (await fsPromises.lstat(output)).isDirectory();
    const target = isDir ? `${output}/config.json` : output;
    const configContents = await (0, utils_1.readJsonFile)(target);
    if (deleteDefaultSession) {
        configContents.defaultSession = undefined;
        await (0, utils_1.writeJsonFile)(target, configContents);
    }
    else if (currentSession) {
        console.log(`The current default session is ${JSON.stringify(configContents.defaultSession)}`);
        process.exit();
    }
    else if (!session) {
        throw new Error('Please provide a --session file');
    }
    else if (session) {
        await (0, utils_1.writeJsonFile)(target, {
            ...configContents,
            defaultSession: await readDefaultSessionFile(session),
        });
    }
}
async function readDefaultSessionFile(defaultSessionFile) {
    let defaultSessionJson;
    try {
        defaultSessionJson = await fsPromises.readFile(defaultSessionFile, {
            encoding: 'utf8',
        });
    }
    catch (error) {
        throw new Error('Could not read the provided file');
    }
    try {
        const session = (0, json_parse_better_errors_1.default)(defaultSessionJson);
        // return top-level "session" if it exists, such as in files created by
        // "File -> Export session"
        return session.session || session;
    }
    catch (error) {
        throw new Error('Could not parse the given default session file');
    }
}
