let db;

// Initialize the database.
function initDatabase() {
  const request = indexedDB.open("DivLoggerDB", 1);

  request.onupgradeneeded = (event) => {
    db = event.target.result;
    if (!db.objectStoreNames.contains("logs")) {
      db.createObjectStore("logs", { autoIncrement: true });
    }
  };

  request.onsuccess = (event) => {
    db = event.target.result;
    console.log("Database initialized");
  };

  request.onerror = (event) => {
    console.error("Database error:", event.target.error);
  };
}

// Save a log entry to the database.
function saveLogToDatabase(data) {
  if (!db) {
    console.error("Database not initialized");
    return;
  }

  const transaction = db.transaction("logs", "readwrite");
  const store = transaction.objectStore("logs");
  store.add(data);

  transaction.oncomplete = () => {
    console.log("Log saved to database");
  };

  transaction.onerror = (event) => {
    console.error("Transaction error:", event.target.error);
  };
}

// Retrieve all log entries.
function viewLogs(callback) {
  if (!db) {
    console.error("Database not initialized");
    return;
  }
  const transaction = db.transaction("logs", "readonly");
  const store = transaction.objectStore("logs");
  const request = store.getAll();
  request.onsuccess = () => {
    callback(request.result);
  };
  request.onerror = (event) => {
    console.error("Error retrieving logs:", event.target.error);
  };
}

// Export logs (returns all logs as JSON).
function exportLogs(callback) {
  viewLogs(callback);
}

// Clear the logs from the database.
function clearDatabase(callback) {
  if (!db) {
    console.error("Database not initialized");
    return;
  }
  const transaction = db.transaction("logs", "readwrite");
  const store = transaction.objectStore("logs");
  const clearRequest = store.clear();
  clearRequest.onsuccess = () => {
    console.log("Database cleared.");
    if (callback) callback();
  };
  clearRequest.onerror = (event) => {
    console.error("Error clearing database:", event.target.error);
  };
}

// Listen for messages from other parts of the extension.
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.type === "log_coordinates") {
    const logEntry = {
      timestamp: new Date().toISOString(),
      coordinates: message.data,
    };
    saveLogToDatabase(logEntry);
  } else if (message.type === "view_logs") {
    viewLogs((logs) => {
      sendResponse({ logs: logs });
    });
    return true; // For asynchronous response.
  } else if (message.type === "export_logs") {
    exportLogs((logs) => {
      sendResponse({ logs: logs });
    });
    return true;
  } else if (message.type === "clear_database") {
    clearDatabase(() => {
      sendResponse({ status: "cleared" });
    });
    return true;
  }
});

// Initialize the database on startup.
initDatabase();
