let db;
let objectStore;

self.onmessage = (e) => {
  const message = e.data;

  switch (message.messageType) {
    case 'WriteCurrentSaveDataToIndexedDB':
      writeCurrentSaveDataToIndexedDB(message.messageData);
      break;
    case 'GetRecoverySaveDataFromIndexedDB':
      getRecoverySaveDataFromIndexedDB();
      break;
  }
};

async function initDB() {
  return new Promise((resolve, reject) => {
    if (db === undefined) {
      const req = indexedDB.open("MyRoomPlansSaves", 1);

      req.onsuccess = () => {
        db = req.result;
        resolve();
      };

      req.onupgradeneeded = (e) => {
        db = e.target.result;
        objectStore = db.createObjectStore("MyRoomPlansSaves", { keyPath: 'saveName' });

        objectStore.createIndex('saveValue', 'saveValue');
        resolve();
      };

      req.onerror = () => {
        console.warn('Unable to load database');
        reject();
      }
    } else {
      resolve();
    }
  });
}

async function getRecoverySaveDataFromIndexedDB() {
  await initDB();
  objectStore = db.transaction(["MyRoomPlansSaves"]).objectStore("MyRoomPlansSaves");

  objectStore.openCursor().onsuccess = (event) => {
    let cursor = event.target.result;

    if (cursor) {
      self.postMessage(cursor.value.saveValue);
    } else {
      self.postMessage(null);
    }
  };
}

async function writeCurrentSaveDataToIndexedDB(data) {
  await initDB();
  objectStore = db.transaction(["MyRoomPlansSaves"], "readwrite").objectStore("MyRoomPlansSaves");

  let request = objectStore.put({saveName: 'recoverySave', saveValue: data});

  request.onsuccess = () => {
    self.postMessage(true);
  };

  request.onerror = () => {
    self.postMessage(null);
    console.warn('Unable to write data to database');
  }
}
