"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.RustSdkAppserviceCryptoStorageProvider = exports.RustSdkCryptoStorageProvider = void 0;
const lowdb = require("lowdb");
const FileSync = require("lowdb/adapters/FileSync");
const mkdirp = require("mkdirp");
const path = require("path");
const sha512 = require("hash.js/lib/hash/sha/512");
const sha256 = require("hash.js/lib/hash/sha/256");
/**
 * A crypto storage provider for the default rust-sdk store (sled, file-based).
 * @category Storage providers
 */
class RustSdkCryptoStorageProvider {
    /**
     * Creates a new rust-sdk storage provider.
     * @param {string} storagePath The *directory* to persist database details to.
     */
    constructor(storagePath) {
        this.storagePath = storagePath;
        this.storagePath = path.resolve(this.storagePath);
        mkdirp.sync(storagePath);
        const adapter = new FileSync(path.join(storagePath, "bot-sdk.json"));
        this.db = lowdb(adapter);
        this.db.defaults({
            deviceId: null,
            rooms: {},
        });
    }
    async getDeviceId() {
        return this.db.get('deviceId').value();
    }
    async setDeviceId(deviceId) {
        this.db.set('deviceId', deviceId).write();
    }
    async getRoom(roomId) {
        const key = sha512().update(roomId).digest('hex');
        return this.db.get(`rooms.${key}`).value();
    }
    async storeRoom(roomId, config) {
        const key = sha512().update(roomId).digest('hex');
        this.db.set(`rooms.${key}`, config).write();
    }
}
exports.RustSdkCryptoStorageProvider = RustSdkCryptoStorageProvider;
/**
 * An appservice crypto storage provider for the default rust-sdk store (sled, file-based).
 * @category Storage providers
 */
class RustSdkAppserviceCryptoStorageProvider extends RustSdkCryptoStorageProvider {
    /**
     * Creates a new rust-sdk storage provider.
     * @param {string} baseStoragePath The *directory* to persist database details to.
     */
    constructor(baseStoragePath) {
        super(path.join(baseStoragePath, "_default"));
        this.baseStoragePath = baseStoragePath;
    }
    storageForUser(userId) {
        // sha256 because sha512 is a bit big for some operating systems
        const key = sha256().update(userId).digest('hex');
        return new RustSdkCryptoStorageProvider(path.join(this.baseStoragePath, key));
    }
}
exports.RustSdkAppserviceCryptoStorageProvider = RustSdkAppserviceCryptoStorageProvider;
//# sourceMappingURL=RustSdkCryptoStorageProvider.js.map