"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const lowdb = require("lowdb");
const FileSync = require("lowdb/adapters/FileSync");
const sha512 = require("hash.js/lib/hash/sha/512");
class SimpleFsStorageProvider {
    constructor(filename, trackTransactionsInMemory = true, maxInMemoryTransactions = 20) {
        this.trackTransactionsInMemory = trackTransactionsInMemory;
        this.maxInMemoryTransactions = maxInMemoryTransactions;
        this.completedTransactions = [];
        const adapter = new FileSync(filename);
        this.db = lowdb(adapter);
        this.db.defaults({
            syncToken: null,
            filter: null,
            appserviceUsers: {},
            appserviceTransactions: {},
        }).write();
    }
    setSyncToken(token) {
        this.db.set('syncToken', token).write();
    }
    getSyncToken() {
        return this.db.get('syncToken').value();
    }
    setFilter(filter) {
        this.db.set('filter', filter).write();
    }
    getFilter() {
        return this.db.get('filter').value();
    }
    addRegisteredUser(userId) {
        const key = sha512().update(userId).digest('hex');
        this.db
            .set(`appserviceUsers.${key}.userId`, userId)
            .set(`appserviceUsers.${key}.registered`, true)
            .write();
    }
    isUserRegistered(userId) {
        const key = sha512().update(userId).digest('hex');
        return this.db.get(`appserviceUsers.${key}.registered`).value();
    }
    isTransactionCompleted(transactionId) {
        if (this.trackTransactionsInMemory) {
            return this.completedTransactions.indexOf(transactionId) !== -1;
        }
        const key = sha512().update(transactionId).digest('hex');
        return this.db.get(`appserviceTransactions.${key}.completed`).value();
    }
    setTransactionCompleted(transactionId) {
        if (this.trackTransactionsInMemory) {
            if (this.completedTransactions.indexOf(transactionId) === -1) {
                this.completedTransactions.push(transactionId);
            }
            if (this.completedTransactions.length > this.maxInMemoryTransactions) {
                this.completedTransactions = this.completedTransactions.reverse().slice(0, this.maxInMemoryTransactions).reverse();
            }
            return;
        }
        const key = sha512().update(transactionId).digest('hex');
        this.db
            .set(`appserviceTransactions.${key}.txnId`, transactionId)
            .set(`appserviceTransactions.${key}.completed`, true)
            .write();
    }
}
exports.SimpleFsStorageProvider = SimpleFsStorageProvider;
