"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.setupRecentAddressesStore = exports.getRecentAddressesStore = exports.RECENT_ADDRESSES_COUNT_LIMIT = void 0;
exports.RECENT_ADDRESSES_COUNT_LIMIT = 12;
let recentAddressesStore = null;
function getRecentAddressesStore() {
    if (recentAddressesStore === null) {
        throw new Error("Recent addresses store instance is null, please call function setupRecentAddressesStore in application initialization");
    }
    return recentAddressesStore;
}
exports.getRecentAddressesStore = getRecentAddressesStore;
function setupRecentAddressesStore(addressesByCurrency, onAddAddressComplete) {
    recentAddressesStore = new RecentAddressesStoreImpl(addressesByCurrency, onAddAddressComplete);
}
exports.setupRecentAddressesStore = setupRecentAddressesStore;
class RecentAddressesStoreImpl {
    addressesByCurrency = {};
    onAddAddressComplete;
    constructor(addressesByCurrency, onAddAddressComplete) {
        this.addressesByCurrency = { ...addressesByCurrency };
        this.onAddAddressComplete = onAddAddressComplete;
    }
    addAddress(currency, address) {
        this.addAddressToCache(currency, address, "triggerCallback");
    }
    syncAddresses(cache) {
        const previousAddresses = { ...this.addressesByCurrency };
        this.addressesByCurrency = { ...cache };
        for (const currency in previousAddresses) {
            for (const address of previousAddresses[currency]) {
                this.addAddressToCache(currency, address, "skipCallback");
            }
        }
        this.onAddAddressComplete(this.addressesByCurrency);
    }
    getAddresses(currency) {
        const addresses = this.addressesByCurrency[currency];
        return addresses ?? [];
    }
    addAddressToCache(currency, address, callbackMode) {
        if (!this.addressesByCurrency[currency]) {
            this.addressesByCurrency[currency] = [];
        }
        const addresses = this.addressesByCurrency[currency];
        const addressIndex = addresses.indexOf(address);
        if (addressIndex !== -1) {
            addresses.splice(addressIndex, 1);
        }
        else if (addresses.length >= exports.RECENT_ADDRESSES_COUNT_LIMIT) {
            addresses.pop();
        }
        addresses.unshift(address);
        this.addressesByCurrency[currency] = [...addresses];
        if (callbackMode === "triggerCallback") {
            this.onAddAddressComplete(this.addressesByCurrency);
        }
    }
}
//# sourceMappingURL=recentAddresses.js.map