"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 semver = require("semver");
const database_1 = require("./database");
const library_utils_1 = require("./features/utils/library-utils");
const Scanner_1 = require("./features/scanner/Scanner");
const { version } = require('../../package.json');
exports.upgraders = {
    '1.2.0-5': 'reset'
};
function runUpgrade(oldOne, version) {
    return __awaiter(this, void 0, void 0, function* () {
        if (semver.gt(version, oldOne)) {
            const requiredUpgrades = Object.keys(exports.upgraders).filter((target) => {
                return semver.gt(target, oldOne);
            });
            if (requiredUpgrades.find((v) => {
                return exports.upgraders[v] == 'reset';
            })) {
                return true;
            }
            yield requiredUpgrades.reduce((acc, val) => {
                return acc.then(() => {
                    return requiredUpgrades[val]();
                });
            }, Promise.resolve());
            return false;
        }
        console.log('\n  Nothing to do, versions match\n');
        return false;
    });
}
exports.runUpgrade = runUpgrade;
function resetLibraries() {
    return __awaiter(this, void 0, void 0, function* () {
        const libraries = new database_1.default('libraries');
        const libs = yield libraries.allDocs();
        yield Promise.all(libs.rows.map((doc) => {
            return library_utils_1.resetLibrary(doc.id);
        }));
    });
}
exports.resetLibraries = resetLibraries;
function rescanAll(onEnterDir) {
    return __awaiter(this, void 0, void 0, function* () {
        const libraries = new database_1.default('libraries');
        const libs = yield libraries.allDocs();
        yield Promise.all(libs.rows.map((doc) => {
            const scanner = new Scanner_1.Scanner(doc.id);
            scanner.on('open_folder', (folder) => {
                onEnterDir(folder);
            });
            return scanner.scan(database_1.default);
        }));
    });
}
exports.rescanAll = rescanAll;
//# sourceMappingURL=upgrader.js.map