import AuthStore from 'stores/Auth';
const storage = {};

const STORAGES = {
    session: sessionStorage,
    local: localStorage,
};

const orgId = AuthStore.getOrganizationId();

Object.keys(STORAGES).forEach(storageKey => {
    storage[storageKey] = {
        setValue(key, value) {
            try {
                STORAGES[storageKey].setItem(`${orgId}.${key}`, JSON.stringify(value));
            } catch (e) {
                // empty
            }
        },
        getValue(key) {
            let value;
            let storeData;

            try {
                storeData = STORAGES[storageKey].getItem(`${orgId}.${key}`) || STORAGES[storageKey].getItem(key);
                value = JSON.parse(storeData);
            } catch (e) {
                // empty
            }

            return value;
        },
        removeValue(key) {
            try {
                STORAGES[storageKey].removeItem(`${orgId}.${key}`);

                if (STORAGES[storageKey].getItem(key)) {
                    STORAGES[storageKey].removeItem(key);
                }
            } catch (e) {
                // empty
            }
        },
    };
});

export default window.ya.connect.storage = storage;
