'use strict';

class FetchHelper {
    storagePrefix = '';
    constructor(namespace = '') {
        this.storagePrefix = namespace;
    }
    async fetchJson(input, init = {}, useCache = false, onCacheUpdated = null) {
        const url = typeof input === 'string' ? input : input.url;
        const cacheKey = url;
        let jsonData = null;
        let cachedData = null;
        if (useCache) {
            cachedData = this.store.get(cacheKey);
            if (cachedData && !cachedData.permanent) {
                if (cachedData.data) {
                    return cachedData.data;
                }
            }
        }
        try {
            const response = await fetch(input, init);
            jsonData = await response.json();
            if (useCache) {
                if (typeof onCacheUpdated === 'function' && cachedData != null) {
                    onCacheUpdated(jsonData);
                }
                this.store.set(cacheKey, this.wrapJson(jsonData, true), true);
                this.store.set(cacheKey, this.wrapJson(jsonData, false), false);
            }
            return jsonData;
        }
        catch (error) {
            console.error(error);
            return null;
        }
    }
    wrapJson(data, permanent = false) {
        const now = new Date();
        return {
            timestamp: now.getTime(),
            time: now.toISOString(),
            data: data,
            permanent: permanent,
        };
    }
    store = {
        get: (key, permanentStorageFirst = false) => {
            const firstProfider = permanentStorageFirst ? window.localStorage : window.sessionStorage;
            const secondProvider = permanentStorageFirst ? window.sessionStorage : window.localStorage;
            let value = firstProfider.getItem(`${this.storagePrefix}-${key}`);
            if (!value) {
                value = secondProvider.getItem(`${this.storagePrefix}-${key}`);
            }
            if (!value) {
                return value;
            }
            if (value.indexOf('{') === 0) {
                try {
                    return JSON.parse(value);
                }
                catch (e) { }
            }
            if (value.indexOf(',') !== -1) {
                return value.split(',');
            }
            return value;
        },
        set: (key, value, permanent = false) => {
            const provider = permanent ? window.localStorage : window.sessionStorage;
            if (typeof value === 'object' && typeof value.length === 'undefined') {
                provider.setItem(`${this.storagePrefix}-${key}`, JSON.stringify(value));
                return;
            }
            provider.setItem(`${this.storagePrefix}-${key}`, value);
        },
        remove: (key) => {
            window.sessionStorage.removeItem(`${this.storagePrefix}-${key}`);
        },
    };
}

exports.FetchHelper = FetchHelper;

//# sourceMappingURL=FetchHelper-2d4c697c.js.map