import getOrganization from './getOrganization';

class ContextStorage {
    constructor(storage) {
        this.storage = storage;
    }

    getKey(key) {
        return `${getOrganization().id}.${key}`;
    }

    setItem(key, value) {
        try {
            this.storage.setItem(this.getKey(key), JSON.stringify(value));
        } catch (e) { /* ignore */ }
    }

    getItem(key) {
        try {
            let storeData = this.storage.getItem(this.getKey(key)) ||
                this.storage.getItem(key);

            return JSON.parse(storeData);
        } catch (e) { /* ignore */ }
    }

    removeItem(key) {
        try {
            this.storage.removeItem(this.getKey(key));

            if (this.storage.getItem(key)) {
                this.storage.removeItem(key);
            }
        } catch (e) { /* ignore */ }
    }
}

export default window.ya.connect.storage = {
    local: new ContextStorage(localStorage),
    session: new ContextStorage(sessionStorage),
};
