export class LocalStorage {
    prefix = '';

    cache = {};

    constructor(prefix = '') {
        this.prefix = prefix ? prefix + '.' : '';
    }

    setItem(key, value) {
        this.cache[key] = value;
        if (window.localStorage) {
            try {
                window.localStorage.setItem(this.prefix + key, JSON.stringify(value));
            } catch (error) {
                // Ignore
            }
        }
    }

    getItem(key, defaultValue = undefined) {
        if (key in this.cache) {
            return this.cache[key];
        }
        if (window.localStorage) {
            try {
                let value = window.localStorage.getItem(this.prefix + key);
                if (value !== null) {
                    value = JSON.parse(value);
                    this.cache[key] = value;
                    return value;
                }
            } catch (error) {
                // Ignore
            }
            return defaultValue;
        }
    }
}
