"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
const crypto_1 = require("crypto");
const fs = require("fs");
const mkdirp = require("mkdirp");
const path = require("path");
const errors_1 = require("../errors");
const util_1 = require("../util");
const compator_1 = require("./compator");
exports.defaultCompactor = new compator_1.ExponentialSaveCompactor({
    baseBucketMs: 1000 * 30,
    bucketIncreaseMultiplier: 1.5,
    bucketMaxMs: 1000 * 60 * 10,
    maxRetentionMs: 1000 * 60 * 60 * 24 * 14,
});
/**
 * Saves manages project save files.
 */
class Saves {
    constructor(project, compactor = exports.defaultCompactor) {
        this.project = project;
        this.compactor = compactor;
    }
    /**
     * Appends as the given blob as a file save.
     */
    append(blob, now = Date.now()) {
        return __awaiter(this, void 0, void 0, function* () {
            const dir = yield this.getSaveDir();
            yield Promise.all([this.trimFiles(dir, now), this.writeBlob(dir, blob)]);
        });
    }
    /**
     * List enumerates all current save files.
     */
    list() {
        return __awaiter(this, void 0, void 0, function* () {
            const files = yield this.listFiles(yield this.getSaveDir());
            return files.map(file => ({
                name: file,
                savedAt: new Date(Number(file)),
            }));
        });
    }
    /**
     * Load opens a save file.
     */
    load(file) {
        return __awaiter(this, void 0, void 0, function* () {
            const filepath = path.join(yield this.getSaveDir(), file);
            if (!fs.existsSync(filepath)) {
                throw new errors_1.SaveNotFoundError();
            }
            return JSON.parse(yield util_1.readFile(filepath));
        });
    }
    /**
     * Loads the most recent save file.
     */
    loadLatest() {
        return __awaiter(this, void 0, void 0, function* () {
            const files = yield this.listFiles(yield this.getSaveDir());
            if (files.length === 0) {
                throw new errors_1.SaveNotFoundError();
            }
            return this.load(files[files.length - 1]);
        });
    }
    listFiles(dir) {
        return __awaiter(this, void 0, void 0, function* () {
            const files = yield util_1.promiseCallback(callback => fs.readdir(dir, callback));
            return files.filter(file => !isNaN(Number(file))).sort((a, b) => Number(a) - Number(b));
        });
    }
    trimFiles(dir, now) {
        return __awaiter(this, void 0, void 0, function* () {
            const files = yield this.listFiles(dir);
            const toCompact = this.compactor.trim(files
                .filter(file => !isNaN(Number(file)))
                .map(file => [new Date(Number(file)), file]), now);
            yield Promise.all(toCompact.map((file) => __awaiter(this, void 0, void 0, function* () { return util_1.promiseCallback(callback => fs.unlink(path.join(dir, file), callback)); })));
        });
    }
    writeBlob(dir, blob, now = Date.now()) {
        return __awaiter(this, void 0, void 0, function* () {
            yield util_1.promiseCallback(callback => fs.writeFile(path.join(dir, String(now)), JSON.stringify(blob), callback));
        });
    }
    getSaveDir() {
        return __awaiter(this, void 0, void 0, function* () {
            const saveDir = path.join(path.dirname(this.project.profile.file), '.miix-data', 'saves', crypto_1.createHash('md5')
                .update(this.project.baseDir())
                .digest('hex'));
            yield util_1.promiseCallback(callback => mkdirp(saveDir, callback));
            return saveDir;
        });
    }
}
exports.Saves = Saves;
