+import { extractTime } from "@/utils/timeControl";
+
+// TODO: show game structure
+//const newItem = [
+// { gameId: "", players: [], timeControl: "", clocks: [] }
+//];
+
+function dbOperation(callback)
+{
+ let db = null;
+ let DBOpenRequest = window.indexedDB.open("vchess", 4);
+
+ DBOpenRequest.onerror = function(event) {
+ alert("Database error: " + event.target.errorCode);
+ };
+
+ DBOpenRequest.onsuccess = function(event) {
+ db = DBOpenRequest.result;
+ callback(db);
+ db.close();
+ };
+
+ DBOpenRequest.onupgradeneeded = function(event) {
+ let db = event.target.result;
+ db.onerror = function(event) {
+ alert("Error while loading database: " + event.target.errorCode);
+ };
+ // Create objectStore for vchess->games
+ db.createObjectStore("games", { keyPath: "gameId" });
+ }
+}
+
+// Optional callback to get error status
+function addGame(game, callback)
+{
+ dbOperation((db) => {
+ let transaction = db.transaction(["games"], "readwrite");
+ if (callback)
+ {
+ transaction.oncomplete = function() {
+ callback({}); //everything's fine
+ }
+ transaction.onerror = function() {
+ callback({errmsg: "addGame failed: " + transaction.error});
+ };
+ }
+ let objectStore = transaction.objectStore("games");
+ objectStore.add(game);
+ });
+}
+
+// Clear current live game from localStorage
+function clear() {
+ localStorage.deleteItem("gameInfo");
+ localStorage.deleteItem("gameState");
+}
+
+// Current live game:
+function getCurrent()
+{
+ return Object.assign({},
+ JSON.parse(localStorage.getItem("gameInfo")),
+ JSON.parse(localStorage.getItem("gameState")));
+}
+
+// Only called internally after a score update
+function transferToDb()
+{
+ addGame(getCurrent(), (err) => {
+ if (!!err.errmsg)
+ return err;
+ clear();
+ });
+}