"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const chalk_1 = tslib_1.__importDefault(require("chalk"));
const command_1 = require("@oclif/command");
const base_1 = tslib_1.__importDefault(require("../base"));
const utils_1 = require("../utils");
const logger_1 = tslib_1.__importDefault(require("../utils/logger"));
const git_1 = require("../utils/git");
const constants_1 = require("../constants");
class Pull extends base_1.default {
    async run() {
        const { flags } = this.parse(Pull);
        this.userConfig = Object.assign(this.userConfig, flags);
        try {
            await utils_1.checkInitStatus();
        }
        catch (err) {
            logger_1.default.log('error', err.message);
            this.exit(1);
        }
        let remoteToPull = flags.remote;
        if (!remoteToPull) {
            const remotes = await git_1.git.getRemotes(true);
            if (remotes.length === 0) {
                logger_1.default.log('error', 'Remote repository has not been configured.');
                this.exit(1);
            }
            else {
                // Select the first remote by default.
                remoteToPull = remotes[0].name;
            }
        }
        try {
            await git_1.git.checkout(constants_1.TUTURE_BRANCH);
            logger_1.default.log('info', `Starting to pull from ${remoteToPull}.`);
            const { files } = await git_1.git.pull(remoteToPull, constants_1.TUTURE_BRANCH);
            if (files.length > 0) {
                // Commit changes to tuture branch.
                logger_1.default.log('success', `Pulled from ${remoteToPull} successfully.`);
            }
            else {
                logger_1.default.log('success', `Already up-to-date with ${remoteToPull}.`);
            }
        }
        catch (err) {
            const { conflicted } = await git_1.git.status();
            if (conflicted.length > 0) {
                logger_1.default.log('error', `Please manually resolve the conflict and run ${chalk_1.default.bold('tuture sync --continue')} to move on.`);
            }
            else {
                // No remote tuture branch.
                logger_1.default.log('error', String(err.message).trim());
            }
            this.exit(1);
        }
    }
}
exports.default = Pull;
Pull.description = 'Pull the remote tuture branch to local';
Pull.flags = {
    help: command_1.flags.help({ char: 'h' }),
    remote: command_1.flags.string({ char: 'r', description: 'name of remote to pull' }),
};
