"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const open_1 = tslib_1.__importDefault(require("open"));
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const get_port_1 = tslib_1.__importDefault(require("get-port"));
const command_1 = require("@oclif/command");
const reload_1 = tslib_1.__importDefault(require("./reload"));
const base_1 = tslib_1.__importDefault(require("../base"));
const logger_1 = tslib_1.__importDefault(require("../utils/logger"));
const server_1 = tslib_1.__importDefault(require("../server"));
const utils_1 = require("../utils");
const git_1 = require("../utils/git");
const collection_1 = require("../utils/collection");
class Up extends base_1.default {
    async fireTutureServer() {
        const port = await get_port_1.default({ port: this.userConfig.port });
        const server = server_1.default(this.userConfig);
        server.listen(port, () => {
            const url = `http://localhost:${port}`;
            logger_1.default.log('success', `Tutorial editor is served on ${url}`);
            // Don't open browser in test environment.
            if (process.env.TEST !== 'yes') {
                open_1.default(url);
            }
        });
    }
    async run() {
        const { flags } = this.parse(Up);
        this.userConfig = Object.assign(this.userConfig, flags);
        try {
            await utils_1.checkInitStatus();
        }
        catch (err) {
            logger_1.default.log('error', err.message);
            this.exit(1);
        }
        // Run sync command if workspace is not prepared.
        if (!fs_extra_1.default.existsSync(collection_1.collectionPath) || !fs_extra_1.default.existsSync(git_1.diffPath)) {
            await reload_1.default.run([]);
        }
        // Trying to load collection for sanity check.
        collection_1.loadCollection();
        this.fireTutureServer();
    }
}
exports.default = Up;
Up.description = 'Render and edit tutorial in browser';
Up.flags = {
    help: command_1.flags.help({ char: 'h' }),
    port: command_1.flags.integer({
        char: 'p',
        description: 'which port to use for editor server',
    }),
};
