"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AdaptableUpgradeHelper = void 0;
const VersionUpgrade17_1 = require("./VersionUpgrade17");
const VersionUpgrade18_1 = require("./VersionUpgrade18");
const EnvVars_1 = require("../EnvVars");
const VersionUpgrade20_1 = require("./VersionUpgrade20");
const VersionUpgrade21_1 = require("./VersionUpgrade21");
const VersionUpgrade22_1 = require("./VersionUpgrade22");
class AdaptableUpgradeHelper {
    currentMajorVersion;
    versionUpgrades;
    logger;
    constructor(logger) {
        this.currentMajorVersion = this.getCurrentMajorVersion(EnvVars_1.ADAPTABLE_VERSION);
        this.logger = logger || this.getConsoleLogger();
        this.versionUpgrades = new Map();
        this.versionUpgrades.set(17, new VersionUpgrade17_1.VersionUpgrade17(this.logger));
        this.versionUpgrades.set(18, new VersionUpgrade18_1.VersionUpgrade18(this.logger));
        this.versionUpgrades.set(20, new VersionUpgrade20_1.VersionUpgrade20(this.logger));
        this.versionUpgrades.set(21, new VersionUpgrade21_1.VersionUpgrade21(this.logger));
        this.versionUpgrades.set(22, new VersionUpgrade22_1.VersionUpgrade22(this.logger));
    }
    static migrateAdaptableState(state, config) {
        const upgradeHelper = new AdaptableUpgradeHelper(config.logger);
        let fromVersion = config?.fromVersion || 16;
        const toVersion = config?.toVersion || upgradeHelper.currentMajorVersion;
        if (fromVersion >= toVersion) {
            console.warn(`The fromVersion (${fromVersion}) should be less than toVersion (${toVersion})!`);
            return state;
        }
        if (fromVersion < 16) {
            // until version 16 we didn't have versioning
            fromVersion = 16;
        }
        const versionUpgrades = Array.from(upgradeHelper.versionUpgrades.keys());
        let updatedState = structuredClone(state);
        for (const version of versionUpgrades) {
            if (version > fromVersion && version <= toVersion) {
                upgradeHelper.logger.info(`Migration to version ${version} started.`);
                updatedState = upgradeHelper.versionUpgrades.get(version).migrateState(updatedState);
                upgradeHelper.logger.info(`Migration to version ${version} completed.`);
            }
        }
        return updatedState;
    }
    getCurrentMajorVersion(version) {
        // is good enough for now, we just need to make sure we don't forget to update it
        return parseInt(version.split('.')[0]) || 22;
    }
    getConsoleLogger() {
        return {
            success: console.log,
            info: console.info,
            warn: console.warn,
            error: console.error,
        };
    }
}
exports.AdaptableUpgradeHelper = AdaptableUpgradeHelper;
