
import idb from "./idb-promised.js"


const dbPromise = createIndexedDB();

function createIndexedDB() {
    if (!('indexedDB' in window)) { return null; }
    return idb.open('dashboardr', 1, function (upgradeDb) {
        if (!upgradeDb.objectStoreNames.contains('events')) {
            const eventsOS = upgradeDb.createObjectStore('events', { keyPath: 'id' });
        }
    });
}

const backSync = {
        saveEventDataLocally: (events) => {
            if (!('indexedDB' in window)) {
                 return null;
            }
            return dbPromise.then(db => {
                const tx = db.transaction('events', 'readwrite');
                const store = tx.objectStore('events');
                return Promise.all(events.map(event => store.put(event)))
                    .catch(() => {
                        tx.abort();
                        throw Error('Events were not added to the store');
                    });
            });
        }

}

export default backSync;


