import setData from "../data/sets/mkm/card-data.json";
import draftData from "../data/draft_mkm.json";
import cardRatings from "../data/sets/mkm/card-ratings-all.json";

import {Elm} from '../src/Main.elm';

function getSetData(db, setCode, callback) {
    const transaction = db.transaction(["sets"], "readwrite");

    const objectStore = transaction.objectStore("sets");
    const request = objectStore.get(setCode);

    request.onerror = (event) => {
        alert("Database error")
    };
    request.onsuccess = (event) => {
        if (request.result === undefined) {
            callback({code: setCode, data: null});
        } else {
            callback({code: setCode, data: request.result.data});
        }
    };
}

const openDBRequest = indexedDB.open("set_database", 2);

openDBRequest.onerror = (event) => {
    alert("Could not open browser database");
};

openDBRequest.onupgradeneeded = (event) => {
    console.log("Upgrading")
    const database = event.target.result;

    const objectStore = database.createObjectStore("sets", {keyPath: "code"});
}

openDBRequest.onsuccess = (event) => {
    const database = event.target.result;
    const app = Elm.Main.init({
        node: document.getElementById('myapp'),
        flags: {
            setData: JSON.stringify(setData),
            draftData: JSON.stringify(draftData),
            cardRatings: JSON.stringify(cardRatings)
        }
    });
    console.log(app);
    console.log(app.ports)

    app.ports.sendDoesSetHaveLocalData.subscribe((setCode) => {
        getSetData(database, setCode, (data) => {
            app.ports.receiveDoesSetHaveLocalData.send(JSON.stringify(data));
        })
    });
};

