export default function Store(objectStoreName) {
    const transact = () => {
        return this.db
            .transaction(objectStoreName, "readwrite")
            .objectStore(objectStoreName)
    }
    
    this.Get = (key) =>  {
        return promisify(
            transact().get(key)
        )
    }
    
    this.Set = (key, value) => {
        return promisify(
            transact().put(value, key)
        )
    }

    return this
}

Store.Open = async (dbName, objectStoreName) => {
    let store = new Store(objectStoreName)
    const request = indexedDB.open(dbName, 2)

    request.onupgradeneeded = (event) => {
        const db = event.target.result
        const objectStore = db.createObjectStore(objectStoreName)

        objectStore.createIndex('value', 'value', { unique: false })
    }

    store.db = await promisify(request)
    return store
}

export function promisify(request) {
    return new Promise((resolve, reject) => {
        request.onsuccess = (event) => {
            resolve(request.result)
        }
        request.onerror = (event) => {
            reject(request.error)
        }
    })
}