(function () {
    'use strict';

    class SoundFontStorage {
        constructor() {
            this.dbName = "DAW_SoundFont_Cache";
            this.storeName = "sf3_buffers";
        }

        async openDB() {
            return new Promise((resolve, reject) => {
                const request = indexedDB.open(this.dbName, 1);
                request.onupgradeneeded = (e) => {
                    const db = e.target.result;
                    if (!db.objectStoreNames.contains(this.storeName)) {
                        db.createObjectStore(this.storeName);
                    }
                };
                request.onsuccess = () => resolve(request.result);
                request.onerror = () => reject(request.error);
            });
        }

        async getBuffer(sfId) {
            try {
                const db = await this.openDB();
                return await new Promise((resolve) => {
                    const tx = db.transaction(this.storeName, "readonly");
                    const store = tx.objectStore(this.storeName);
                    const req = store.get(sfId);
                    req.onsuccess = () => resolve(req.result || null);
                    req.onerror = () => resolve(null);
                });
            } catch (e) {
                return null;
            }
        }

        async saveBuffer(sfId, arrayBuffer) {
            try {
                const db = await this.openDB();
                return await new Promise((resolve, reject) => {
                    const tx = db.transaction(this.storeName, "readwrite");
                    const store = tx.objectStore(this.storeName);
                    const req = store.put(arrayBuffer, sfId);
                    req.onsuccess = () => resolve(true);
                    req.onerror = () => reject(req.error);
                });
            } catch (e) {
                return false;
            }
        }
    }

    window.SonicSFStorage = new SoundFontStorage();
})();
