"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const chalk_1 = tslib_1.__importDefault(require("chalk"));
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 base_1 = tslib_1.__importDefault(require("../base"));
const logger_1 = tslib_1.__importDefault(require("../utils/logger"));
const reload_1 = tslib_1.__importDefault(require("./reload"));
const server_1 = tslib_1.__importDefault(require("../server"));
const utils_1 = require("../utils");
const assets_1 = require("../utils/assets");
const constants_1 = require("../constants");
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);
        if (!(await utils_1.isInitialized())) {
            logger_1.default.log('error', `Tuture is not initialized. Run ${chalk_1.default.bold('tuture init')} to initialize.`);
            this.exit(1);
        }
        // Run reload command if .tuture directory is empty.
        if (fs_extra_1.default.readdirSync(constants_1.TUTURE_ROOT).length === 0) {
            await reload_1.default.run([]);
        }
        // Trying to load tuture.yml for sanity check.
        await collection_1.loadCollection();
        // Background interval to synchronize assets.
        assets_1.syncImages();
        setInterval(assets_1.syncImages, this.userConfig.assetsSyncInterval);
        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',
    }),
};
