"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = useSyncTargetUpgrade;
const shim_1 = require("../../../shim");
const MigrationHandler_1 = require("../MigrationHandler");
const Setting_1 = require("../../../models/Setting");
const registry_1 = require("../../../registry");
const LockHandler_1 = require("../LockHandler");
const { useEffect, useState } = shim_1.default.react();
function useSyncTargetUpgrade() {
    const [upgradeResult, setUpgradeResult] = useState({
        done: false,
        error: null,
    });
    async function upgradeSyncTarget() {
        registry_1.reg.logger().info('useSyncTargetUpgrade: Starting process...');
        let error = null;
        try {
            registry_1.reg.logger().info('useSyncTargetUpgrade: Acquire synchronizer...');
            const synchronizer = await registry_1.reg.syncTarget().synchronizer();
            registry_1.reg.logger().info('useSyncTargetUpgrade: Create migration handler...');
            const migrationHandler = new MigrationHandler_1.default(synchronizer.api(), registry_1.reg.db(), synchronizer.lockHandler(), (0, LockHandler_1.appTypeToLockType)(Setting_1.default.value('appType')), Setting_1.default.value('clientId'));
            registry_1.reg.logger().info('useSyncTargetUpgrade: Start upgrade...');
            await migrationHandler.upgrade();
        }
        catch (e) {
            error = e;
        }
        registry_1.reg.logger().info('useSyncTargetUpgrade: Error:', error);
        if (!error) {
            Setting_1.default.setValue('sync.upgradeState', Setting_1.default.SYNC_UPGRADE_STATE_IDLE);
            await Setting_1.default.saveAll();
        }
        setUpgradeResult({
            done: true,
            error: error,
        });
    }
    useEffect(() => {
        void upgradeSyncTarget();
    }, []);
    return upgradeResult;
}
//# sourceMappingURL=useSyncTargetUpgrade.js.map