function openDatabase() {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open("DivLoggerDB", 1);
    request.onsuccess = (event) => resolve(event.target.result);
    request.onerror = (event) => reject(event.target.error);
  });
}

function fetchLogs() {
  return new Promise(async (resolve, reject) => {
    const db = await openDatabase();
    const transaction = db.transaction("logs", "readonly");
    const store = transaction.objectStore("logs");
    const logs = [];
    const cursorRequest = store.openCursor();
    cursorRequest.onsuccess = (event) => {
      const cursor = event.target.result;
      if (cursor) {
        logs.push(cursor.value);
        cursor.continue();
      } else {
        resolve(logs);
      }
    };
    cursorRequest.onerror = (event) => reject(event.target.error);
  });
}

function clearDatabase() {
  openDatabase().then(db => {
    const transaction = db.transaction("logs", "readwrite");
    const store = transaction.objectStore("logs");
    const clearRequest = store.clear();
    clearRequest.onsuccess = () => {
      console.log("Database cleared");
      document.getElementById("logs").textContent = "Database cleared!";
    };
    clearRequest.onerror = (event) => {
      console.error("Error clearing database:", event.target.error);
    };
  });
}

function displayLogs(logs) {
  const pre = document.getElementById("logs");
  pre.textContent = JSON.stringify(logs, null, 2);
}

function exportLogs(logs) {
  const blob = new Blob([JSON.stringify(logs, null, 2)], { type: "application/json" });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `div_logs_${Date.now()}.json`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
}

// Attach event listeners for the log-related buttons.
document.getElementById("view-logs").addEventListener("click", async () => {
  const logs = await fetchLogs();
  displayLogs(logs);
});

document.getElementById("export-logs").addEventListener("click", async () => {
  const logs = await fetchLogs();
  exportLogs(logs);
});

document.getElementById("clear-db").addEventListener("click", () => {
  clearDatabase();
});

// Functions to send messages to start/stop listening.
document.getElementById("start-listening").addEventListener("click", () => {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    if (tabs.length > 0) {
      chrome.tabs.sendMessage(
        tabs[0].id,
        { type: "start_listening" },
        (response) => {
          if (chrome.runtime.lastError) {
            console.error(chrome.runtime.lastError.message);
            return;
          }
        }
      );
    }
  });
});

document.getElementById("stop-listening").addEventListener("click", () => {
  chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
    if (tabs.length > 0) {
      chrome.tabs.sendMessage(
        tabs[0].id,
        { type: "stop_listening" },
        (response) => {
          if (chrome.runtime.lastError) {
            console.error(chrome.runtime.lastError.message);
            return;
          }
        }
      );
    }
  });
});
