"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const chalk_1 = tslib_1.__importDefault(require("chalk"));
const fs_extra_1 = tslib_1.__importDefault(require("fs-extra"));
const path_1 = tslib_1.__importDefault(require("path"));
const logger_1 = tslib_1.__importDefault(require("./logger"));
const git_1 = require("./git");
const constants_1 = require("../constants");
const assets_1 = require("./assets");
exports.collectionPath = path_1.default.join(process.env.TUTURE_PATH || process.cwd(), constants_1.TUTURE_ROOT, constants_1.COLLECTION_PATH);
exports.collectionCheckpoint = path_1.default.join(process.env.TUTURE_PATH || process.cwd(), constants_1.TUTURE_ROOT, constants_1.COLLECTION_CHECKPOINT);
function hasTutureChangedSinceCheckpoint() {
    if (!fs_extra_1.default.existsSync(exports.collectionCheckpoint)) {
        return false;
    }
    return !fs_extra_1.default
        .readFileSync(exports.collectionPath)
        .equals(fs_extra_1.default.readFileSync(exports.collectionCheckpoint));
}
exports.hasTutureChangedSinceCheckpoint = hasTutureChangedSinceCheckpoint;
/**
 * Whether the local tuture branch exists.
 */
async function hasLocalTutureBranch() {
    return (await git_1.git.branchLocal()).all.includes(constants_1.TUTURE_BRANCH);
}
exports.hasLocalTutureBranch = hasLocalTutureBranch;
/**
 * Whether the remote tuture branch exists.
 */
async function hasRemoteTutureBranch() {
    const remote = await git_1.git.remote([]);
    if (!remote) {
        logger_1.default.log('warning', 'No remote found for this repository.');
        return false;
    }
    const remoteBranch = `remotes/${remote.trim()}/${constants_1.TUTURE_BRANCH}`;
    if (!(await git_1.git.branch({ '-a': true })).all.includes(remoteBranch)) {
        logger_1.default.log('warning', 'No remote tuture branch.');
        return false;
    }
    return true;
}
exports.hasRemoteTutureBranch = hasRemoteTutureBranch;
/**
 * Load collection.
 */
async function loadCollection(fromBranch = false) {
    if (!fs_extra_1.default.existsSync(exports.collectionPath)) {
        await initializeTutureBranch();
        await git_1.git.checkout(constants_1.TUTURE_BRANCH);
        if (!fs_extra_1.default.existsSync(constants_1.COLLECTION_PATH)) {
            logger_1.default.log('error', `Cannot load tuture. Please run ${chalk_1.default.bold('tuture init')} to initialize.`);
            await git_1.git.checkout('master');
            process.exit(1);
        }
        fs_extra_1.default.copySync(constants_1.COLLECTION_PATH, exports.collectionPath);
        if (fs_extra_1.default.existsSync(constants_1.ASSETS_JSON_PATH)) {
            fs_extra_1.default.copySync(constants_1.ASSETS_JSON_PATH, assets_1.assetsTablePath);
        }
    }
    if (fromBranch && fs_extra_1.default.existsSync(constants_1.COLLECTION_PATH)) {
        return JSON.parse(fs_extra_1.default.readFileSync(constants_1.COLLECTION_PATH).toString());
    }
    return JSON.parse(fs_extra_1.default.readFileSync(exports.collectionPath).toString());
}
exports.loadCollection = loadCollection;
/**
 * Save the entire collection back to workspace.
 */
function saveCollection(collection) {
    fs_extra_1.default.writeFileSync(exports.collectionPath, JSON.stringify(collection, null, 2));
}
exports.saveCollection = saveCollection;
/**
 * Fetch tuture branch from remote.
 */
async function initializeTutureBranch() {
    const { all: allBranches } = await git_1.git.branch({ '-a': true });
    // Already exists.
    if (allBranches.includes(constants_1.TUTURE_BRANCH)) {
        return;
    }
    const remoteBranchIndex = allBranches
        .map((branch) => branch.split('/').slice(-1)[0])
        .indexOf(constants_1.TUTURE_BRANCH);
    if (remoteBranchIndex < 0) {
        await git_1.git.branch([constants_1.TUTURE_BRANCH]);
        logger_1.default.log('info', 'New tuture branch has been created.');
    }
    else {
        const [_, remote, branch] = allBranches[remoteBranchIndex].split('/');
        await git_1.git.fetch(remote, branch);
        logger_1.default.log('success', 'Remote tuture branch has been fetched.');
    }
}
exports.initializeTutureBranch = initializeTutureBranch;
async function saveCheckpoint() {
    // Copy the last committed file.
    fs_extra_1.default.copySync(exports.collectionPath, exports.collectionCheckpoint, { overwrite: true });
    if (fs_extra_1.default.existsSync(assets_1.assetsTablePath)) {
        fs_extra_1.default.copySync(assets_1.assetsTablePath, assets_1.assetsTableCheckpoint, {
            overwrite: true,
        });
    }
}
exports.saveCheckpoint = saveCheckpoint;
