"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const chalk_1 = tslib_1.__importDefault(require("chalk"));
const http_1 = tslib_1.__importDefault(require("http"));
const command_1 = require("@oclif/command");
const base_1 = tslib_1.__importDefault(require("../base"));
const logger_1 = tslib_1.__importDefault(require("../utils/logger"));
const utils_1 = require("../utils");
const collection_1 = require("../utils/collection");
const assets_1 = require("../utils/assets");
class Reload extends base_1.default {
    // Notify server to reload.
    async notifyServer() {
        const url = `http://localhost:${this.userConfig.port}/reload`;
        return new Promise((resolve, _) => {
            http_1.default
                .get(url, (res) => {
                const { statusCode } = res;
                if (statusCode === 200) {
                    logger_1.default.log('success', 'Server is ready to reload.');
                }
                resolve();
            })
                .on('error', () => {
                resolve();
            });
        });
    }
    async run() {
        this.parse(Reload);
        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);
        }
        if (collection_1.hasTutureChangedSinceCheckpoint() ||
            assets_1.hasAssetsChangedSinceCheckpoint()) {
            logger_1.default.log('error', 'You have uncommitted changes. Commit them with tuture commit.');
            this.exit(1);
        }
        try {
            const collection = await collection_1.loadCollection(true);
            const currentSteps = await utils_1.makeSteps(this.userConfig.ignoredFiles);
            const lastArticleId = collection.articles.slice(-1)[0].id;
            currentSteps.forEach((step) => {
                // For newly added steps, assign it to the last article.
                if (!collection.steps.map((step) => step.id).includes(step.id)) {
                    step.articleId = lastArticleId;
                }
            });
            collection.steps = utils_1.mergeSteps(collection.steps, currentSteps);
            collection_1.saveCollection(collection);
            // Download assets if necessary.
            assets_1.syncImages();
            // Copy the last committed file.
            await collection_1.saveCheckpoint();
            logger_1.default.log('success', 'Reload complete!');
        }
        catch (err) {
            logger_1.default.log('error', err.message);
            this.exit(1);
        }
    }
}
exports.default = Reload;
Reload.description = 'Sync tuture files with current repo';
Reload.flags = {
    help: command_1.flags.help({ char: 'h' }),
};
