let endpointUrl = "https://api.workstatus.io/api/v1/";

// let endpointUrl = 'https://api.dev.workstatus.io/api/v1/';

// function createDb() {
//   debugger
//   return new Promise((resolve, reject) => {
//     const dbName = "wstracker_new_db";

//     // Delete the existing database
//     // const deleteRequest = indexedDB.deleteDatabase(dbName);

//     deleteRequest.onsuccess = () => {

//       // Open the database after deletion
//       let idb = indexedDB.open(dbName, 1);

//       idb.onupgradeneeded = (e) => {
//         let res = idb.result;

//         const SSLink = res.createObjectStore("SSLink", { autoIncrement: true });
//         const taskStore = res.createObjectStore("taskStore", { autoIncrement: true });
//         const AwsLink = res.createObjectStore("AwsLink", { autoIncrement: true });
//         const SyncDataTimer = res.createObjectStore("SyncDataTimer", { autoIncrement: true });
//         const activityIntervals = res.createObjectStore("activityIntervals", { autoIncrement: true });
//         const idleIntervals = res.createObjectStore("idleIntervals", { autoIncrement: true });
//         const currentTimerData = res.createObjectStore("currentTimerData", { autoIncrement: true });
//         const projectStore = res.createObjectStore("project_list", { autoIncrement: true });
//         const todoStore = res.createObjectStore("todo_list", { autoIncrement: true });
//         todoStore.createIndex("projectidindx", "project_id", { unique: false });

//         const timerStore = res.createObjectStore("timer_data", { autoIncrement: true });
//         timerStore.createIndex("todoindx", "todo_id", { unique: false });
//         timerStore.createIndex("projectindx", "projectId", { unique: false });
//         timerStore.createIndex("breakidindx", "break_id", { unique: false });

//         const intervalStore = res.createObjectStore("interval_data", { autoIncrement: true });
//         intervalStore.createIndex("timerindx", "timer_data_id", { unique: false });

//         const objectStore = res.createObjectStore("userDetails", { autoIncrement: true });
//         objectStore.createIndex("nameindx", "name", { unique: false });

//         const screenshotInterval = res.createObjectStore("screenshot_interval", { autoIncrement: true });
//         const current_data = res.createObjectStore("current_data", { autoIncrement: true });
//         const totalTime = res.createObjectStore("totalTime", { autoIncrement: true });
//         totalTime.createIndex("projectidindx", "project_id", { unique: false });
//         totalTime.createIndex("todoidindx", "todo_id", { unique: false });

//         const syncTimer = res.createObjectStore("syncTimer", { autoIncrement: true });
//         syncTimer.createIndex("projectidindx", "projectId", { unique: false });
//         syncTimer.createIndex("todoidindx", "todoId", { unique: false });

//         resolve("DB created successfully!");
//       };

//       idb.onsuccess = () => {
//         resolve("DB created successfully!");
//       };

//       idb.onerror = (e) => {
//         console.error("Database error:", e.target.error);
//         reject(e.target.error);
//       };
//     };

//     deleteRequest.onerror = (e) => {
//       console.error("Error deleting database:", e.target.error);
//       reject(e.target.error);
//     };
//   });
// }

// function checkChanageDatehtml() {
//   chrome.storage.local.get(["start_time"]).then((strattimeresult) => {
//     chrome.storage.local.get(["time_changed"]).then((timechangedresult) => {
//       if (timechangedresult.time_changed == 0) {
//         // console.warn(strattimeresult.start_time);
//         let startDate = moment(strattimeresult.start_time).format("YYYY-MM-DD");
//         let todayDate = moment().format("YYYY-MM-DD");
//         if (startDate != todayDate) {
//           let newStartTime = moment()
//             .startOf("day")
//             .format("YYYY-MM-DD HH:mm:ss");
//           chrome.storage.local.set({ start_time: newStartTime });
//           setConfigDataTimerDateChangeNew();
//         }
//       }
//     });
//   });
// }
// checkChanageDatehtml();

async function addLog(log, time) {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open("wstracker_new_db", 1);

    request.onsuccess = () => {
      const db = request.result;
      const transaction = db.transaction("logger", "readwrite");
      const store = transaction.objectStore("logger");

      const addRequest = store.add({ log, time });

      addRequest.onsuccess = () => resolve("Log added successfully");
      addRequest.onerror = (event) =>
        reject("Error adding log: " + event.target.error);
    };

    request.onerror = (event) =>
      reject("Error opening database: " + event.target.error);
  });
}

function createDb() {
  try {
    return new Promise((resolve, reject) => {
      let idb = indexedDB.open("wstracker_new_db");
      idb.onupgradeneeded = (e) => {
        let res = idb.result;
        const SSLink = res.createObjectStore("SSLink", {
          autoIncrement: true,
        });

        const logger = res.createObjectStore("logger", {
          autoIncrement: true,
        });
        const TodaysStartTime = res.createObjectStore("todayStartTime", {
          autoIncrement: true,
        });
        const idleHandled = res.createObjectStore("idle_handled", {
          autoIncrement: true,
        });
        const taskStore = res.createObjectStore("taskStore", {
          autoIncrement: true,
        });
        const AwsLink = res.createObjectStore("AwsLink", {
          autoIncrement: true,
        });
        const SyncDataTimer = res.createObjectStore("SyncDataTimer", {
          autoIncrement: true,
        });
        const activityIntervals = res.createObjectStore("activityIntervals", {
          autoIncrement: true,
        });
        const idleIntervals = res.createObjectStore("idleIntervals", {
          autoIncrement: true,
        });
        const currentTimerData = res.createObjectStore("currentTimerData", {
          autoIncrement: true,
        });

        const projectStore = res.createObjectStore("project_list", {
          autoIncrement: true,
        });
        const todoStore = res.createObjectStore("todo_list", {
          autoIncrement: true,
        });
        todoStore.createIndex("projectidindx", "project_id", { unique: false });
        const timerStore = res.createObjectStore("timer_data", {
          autoIncrement: true,
        });
        timerStore.createIndex("todoindx", "todo_id", { unique: false });
        timerStore.createIndex("projectindx", "projectId", { unique: false });
        timerStore.createIndex("breakidindx", "break_id", { unique: false });
        const intervalStore = res.createObjectStore("interval_data", {
          autoIncrement: true,
        });
        intervalStore.createIndex("timerindx", "timer_data_id", {
          unique: false,
        });
        const objectStore = res.createObjectStore("userDetails", {
          autoIncrement: true,
        });
        objectStore.createIndex("nameindx", "name", { unique: false });
        const screenshotInterval = res.createObjectStore(
          "screenshot_interval",
          {
            autoIncrement: true,
          }
        );
        const current_data = res.createObjectStore("current_data", {
          autoIncrement: true,
        });
        const totalTime = res.createObjectStore("totalTime", {
          autoIncrement: true,
        });
        totalTime.createIndex("projectidindx", "project_id", { unique: false });
        totalTime.createIndex("todoidindx", "todo_id", { unique: false });
        const syncTimer = res.createObjectStore("syncTimer", {
          autoIncrement: true,
        });
        syncTimer.createIndex("projectidindx", "projectId", { unique: false });
        syncTimer.createIndex("todoidindx", "todoId", { unique: false });
        resolve("DB created successfully!");
      };
      idb.onsuccess = () => {
        let res = idb.result;

        if (
          !res.objectStoreNames.contains("project_list") || // Check if "project_list" doesn't exist
          (() => {
            const transaction = res.transaction(["project_list"], "readonly");
            const store = transaction.objectStore("project_list");
            const request = store.count();
            let isNull = false;

            request.onsuccess = function () {
              isNull = request.result === 0;
            };

            request.onerror = function () {
              console.error("Error checking 'project_list'");
            };

            return isNull;
          })()
        ) {
          const projectStore = res.createObjectStore("project_list", {
            autoIncrement: true,
          });
          const todoStore = res.createObjectStore("todo_list", {
            autoIncrement: true,
          });
          todoStore.createIndex("projectidindx", "project_id", {
            unique: false,
          });
          const timerStore = res.createObjectStore("timer_data", {
            autoIncrement: true,
          });
          timerStore.createIndex("todoindx", "todo_id", { unique: false });
          timerStore.createIndex("projectindx", "projectId", { unique: false });
          timerStore.createIndex("breakidindx", "break_id", { unique: false });
          const intervalStore = res.createObjectStore("interval_data", {
            autoIncrement: true,
          });
          intervalStore.createIndex("timerindx", "timer_data_id", {
            unique: false,
          });
          const objectStore = res.createObjectStore("userDetails", {
            autoIncrement: true,
          });
          objectStore.createIndex("nameindx", "name", { unique: false });
          const screenshotInterval = res.createObjectStore(
            "screenshot_interval",
            {
              autoIncrement: true,
            }
          );
          const current_data = res.createObjectStore("current_data", {
            autoIncrement: true,
          });
          const totalTime = res.createObjectStore("totalTime", {
            autoIncrement: true,
          });
          totalTime.createIndex("projectidindx", "project_id", {
            unique: false,
          });
          totalTime.createIndex("todoidindx", "todo_id", { unique: false });
          const syncTimer = res.createObjectStore("syncTimer", {
            autoIncrement: true,
          });
          syncTimer.createIndex("projectidindx", "projectId", {
            unique: false,
          });
          syncTimer.createIndex("todoidindx", "todoId", { unique: false });
          resolve("DB created successfully!");
        } else {
          resolve("DB created successfully!");
        }
      };
    });
  } catch (err) {
    reject(err);
    return false;
  }
}

async function getDataDB(tbl) {
  return new Promise(function (resolve, reject) {
    let idb = indexedDB.open("wstracker_new_db");
    idb.onsuccess = () => {
      let res = idb.result;
      try {
        let tx = res.transaction(tbl, "readonly");

        let store = tx.objectStore(tbl);
        let cursor = store.openCursor();
        cursor.onsuccess = () => {
          let curRes = cursor.result;
          if (curRes) {
            resolve(curRes);
          } else {
            //  resolve('nodb');
            reject(Error("Error text"));
          }
        };
      } catch (e) {
        reject("nodb");
      }
    };
  });
}

function getCurrentDateTime() {
  return moment(new Date()).format("YYYY-MM-DD HH:mm:ss");
}

const getSubtractTimer = async () => {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get("subtractTimer", (result) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError); // Reject if there's an error
      } else {
        resolve(result.subtractTimer || 0); // Resolve with the data or null
      }
    });
  });
};

const getSubtractBoolean = async () => {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get("subtractBoolean", (result) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError); // Reject if there's an error
      } else {
        resolve(result.subtractBoolean || 0); // Resolve with the data or null
      }
    });
  });
};

async function setUserdata(tbl, value, version) {
  try {
    let idb = indexedDB.open("wstracker_new_db", 1);
    idb.onsuccess = async () => {
      let res = idb.result;
      let tx = res.transaction(tbl, "readwrite");
      let store = tx.objectStore(tbl);
      const lastinsertdata = store.put(value);
      res.close();
      setTimeout(() => {
        return lastinsertdata.result;
      }, 100);
    };
  } catch (err) {
    return false;
  }
}

const getIsIdleSubtract = async () => {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get("isIdleSub", (result) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError); // Reject if there's an error
      } else {
        resolve(result.isIdleSub || 0); // Resolve with the data or null
      }
    });
  });
};

// -------------AWS LOGIC---------------

async function updateSSLinkById(id, newLink) {
  return new Promise((resolve, reject) => {
    try {
      let idb = indexedDB.open("wstracker_new_db", 1);

      idb.onsuccess = () => {
        let db = idb.result;
        let tx = db.transaction("SSLink", "readwrite");
        let store = tx.objectStore("SSLink");

        // Get the record by id
        let getRequest = store.get(id);

        getRequest.onsuccess = () => {
          if (getRequest.result) {
            let record = getRequest.result;
            record.SSLink = newLink; // Modify only the SSLink field

            // Update the record in the store
            let updateRequest = store.put(record);

            updateRequest.onsuccess = () => {
              resolve(updateRequest.result); // Resolve on success
            };

            updateRequest.onerror = () => {
              reject(updateRequest.error); // Reject on update error
            };
          } else {
            reject(new Error("Record not found")); // Handle case where id is not found
          }
        };

        getRequest.onerror = () => {
          reject(getRequest.error); // Reject on get error
        };
      };

      idb.onerror = () => {
        reject(idb.error); // Handle database connection error
      };
    } catch (err) {
      reject(err); // Handle synchronous errors
    }
  });
}

let isProcessing = false; // Prevent concurrent processing

function isInternetStatus() {
  return navigator.onLine;
}

// Utility function to promisify chrome.storage.local.get
function getStorage(key) {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get(key, function (result) {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError);
      } else {
        resolve(result);
      }
    });
  });
}

// Utility function to promisify chrome.storage.local.set
function setStorage(data) {
  return new Promise((resolve, reject) => {
    chrome.storage.local.set(data, function () {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError);
      } else {
        resolve();
      }
    });
  });
}

async function addData(link, key) {
  return new Promise((resolve, reject) => {
    const idb = indexedDB.open("wstracker_new_db", 1);

    idb.onsuccess = () => {
      const db = idb.result;
      const tx = db.transaction("AwsLink", "readwrite");
      const store = tx.objectStore("AwsLink");

      const data = { AwsLink: link };
      const request = store.put(data, key);

      request.onsuccess = () => resolve(request.result);
      request.onerror = () => reject(request.error);
    };

    idb.onerror = () => reject(idb.error);
  });
}

// Add a single entry to chrome.storage.local under 'aws'
async function addSingleEntry(key, value) {
  try {
    const result = await getStorage("aws");
    let awsData = result.aws || []; // If no data exists, initialize with an empty array

    let newEntry = {};
    newEntry[key] = value; // Create an object with the provided key-value pair
    awsData.push(newEntry); // Add the new entry to the array

    await setStorage({ aws: awsData }); // Update the storage with the new array
  } catch (error) {
    console.error("Error adding entry:", error);
  }
}

async function applyBlurInBackground(imageDataUrl) {
  if (!imageDataUrl) return null; // Return null if the input is null

  return new Promise((resolve) => {
    try {
      const img = new Image();
      img.onload = () => {
        try {
          const canvas = new OffscreenCanvas(img.width, img.height);
          const ctx = canvas.getContext("2d");

          ctx.filter = "blur(4px)"; // Apply blur effect
          ctx.drawImage(img, 0, 0);

          canvas
            .convertToBlob({ type: "image/png" })
            .then((blob) => {
              const reader = new FileReader();
              reader.onloadend = () => resolve(reader.result); // Return blurred image as data URL
              reader.onerror = () => resolve(null);
              reader.readAsDataURL(blob);
            })
            .catch(() => resolve(null));
        } catch {
          resolve(null);
        }
      };
      img.onerror = () => resolve(null);
      img.src = imageDataUrl;
    } catch {
      resolve(null);
    }
  });
}

// async function ImageToS3(url) {
//   if (!url) return;

//   try {
//     const response = await fetch(url);
//     const blob = await response.blob();
//     const fileName = url.split("/").pop();
//     const file = new File([blob], fileName, { type: blob.type });

//     const bucketName = "wspythontest";
//     const region = "ap-south-1";
//     const accessKeyId = "AKIAW3ZDPNJ5TYBZ4VGN";
//     const secretAccessKey = "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";

//     const s3 = new AWS.S3({
//       region,
//       accessKeyId,
//       secretAccessKey,
//     });

//     const params = {
//       Bucket: bucketName,
//       Key: fileName,
//       Body: file,
//       ContentType: file.type,
//     };

//     return new Promise((resolve, reject) => {
//       s3.upload(params, async (err, data) => {
//         if (err) {
//           console.error("Upload failed:", err);
//           reject(err);
//         } else {
//           // await addSingleEntry(key, data.Location);
//           // await addData(data.Location, key); // Save the S3 URL
//           resolve(data);
//         }
//       });
//     });
//   } catch (error) {
//     console.error("Error during S3 upload:", error);
//     throw error;
//   }
// }

const getAWSDetail = async () => {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get("config", (result) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError); // Reject if there's an error
      } else {
        resolve(result.config || null); // Resolve with the data or null
      }
    });
  });
};
async function ImageToS3(url) {
  if (!url) return null; // Return null if no URL is provided

  try {
    const response = await fetch(url);
    if (!response.ok) {
      console.error(`Failed to fetch the image. Status: ${response.status}`);
      return null;
    }

    const blob = await response.blob();
    const fileName = url.split("/").pop();
    const file = new File([blob], fileName, { type: blob.type });

    const awsData = await getAWSDetail();
    const bucketName = awsData.BUCKET;
    const region = awsData.DEFAULT_REGION;
    const accessKeyId = awsData.ACCESS_KEY;
    const secretAccessKey = awsData.SECRET_ACCESS_KEY;

    const s3 = new AWS.S3({
      region,
      accessKeyId,
      secretAccessKey,
    });

    const params = {
      Bucket: bucketName,
      Key: fileName,
      Body: file,
      ContentType: file.type,
    };

    return new Promise((resolve) => {
      s3.upload(params, async (err, data) => {
        if (err) {
          console.error("Upload failed:", err);
          resolve(null); // Return null if the upload fails
        } else {
          resolve(data);
        }
      });
    });
  } catch (error) {
    console.error("Error during S3 upload:", error);
    await addLog("Error - " + error, moment().format("YYYY-MM-DD HH:mm:ss"));
    return null; // Return null if an exception occurs
  }
}

let key = 0;
async function fetchEntriesAndProcess() {
  const idb = indexedDB.open("wstracker_new_db");

  return new Promise((resolve, reject) => {
    idb.onsuccess = () => {
      const db = idb.result;
      const tx = db.transaction("SSLink", "readwrite");
      const store = tx.objectStore("SSLink");

      const entries = [];
      const cursor = store.openCursor();
      cursor.onsuccess = async () => {
        const curRes = cursor.result;
        if (curRes && key < curRes.key) {
          entries.push({
            link: curRes.value.SSLink,
            key: curRes.key,
            isBlur: curRes.value.isBlur,
          });
          key = curRes.key;
          // await curRes.delete();
          curRes.continue();
        } else {
          resolve(entries);
        }
      };

      cursor.onerror = (e) => reject(e);
    };

    idb.onerror = (e) => reject(e);
  });
}

async function processAndMoveEntries() {
  if (isProcessing) {
    console.warn("Process already running. Skipping this cycle.");
    return;
  }

  isProcessing = true;
  try {
    const entries = await fetchEntriesAndProcess();

    if (entries && entries.length > 0) {

      for (const entry of entries) {
        try {
          if (entry.isBlur == 1) {
            let newLink = await applyBlurInBackground(entry.link);
            await updateSSLinkById(entry.key, newLink);
            await ImageToS3(newLink, entry.key);
          } else {
            await ImageToS3(entry.link, entry.key);
          }
        } catch (error) {
          console.error("Error processing entry:", entry, error);
        }
      }
    } else {
    }
  } catch (error) {
    console.error("Error during processing:", error);
  } finally {
    isProcessing = false;
  }
}

// setInterval(async () => {
//   if (isInternetStatus()) {
//     await processAndMoveEntries();
//   }
// }, 5000); // Adjusted interval for better batching

// chrome.runtime.sendMessage({ action: "uploadToAWS" });
// chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
//   try {
//     if (request.action === "uploadToAWS") {
//       await processAndMoveEntries();
//     }
//   } catch (error) {
//     console.error("Error in message listener:", error);
//     sendResponse({ message: "An error occurred.", error: error.message });
//   }
//   return true;
// });

// Function to process SSLink and store modified links in awsLink
async function processAndStoreAwsLinks() {
  const result = await chrome.storage.local.get({ SSLink: [], awsLink: [] });
  let ssLinks = result.SSLink;
  const awsLinks = result.awsLink;

  // Process each item in SSLink
  for (const item of ssLinks) {
    let modifiedLink;

    if (item.isBlur === 1) {
      modifiedLink = await applyBlurInBackground(item.link);
      modifiedLink = await ImageToS3(modifiedLink);
    } else {
      modifiedLink = await ImageToS3(item.link);
    }

    // Add the processed link to awsLink
    awsLinks.push({ id: item.id, link: modifiedLink, isBlur: item.isBlur });
  }

  // Remove processed items from SSLink
  ssLinks = ssLinks.filter(
    (item) => !awsLinks.some((awsItem) => awsItem.id === item.id)
  );

  // Save the updated SSLink and awsLink to storage
  await chrome.storage.local.set({ awsLink: awsLinks, SSLink: ssLinks });
}

// chrome.alarms.create("awsLinkProcessor", {
//   periodInMinutes: 1 / 12, // 5 seconds (1 min / 12 = 5 sec)
// });

// chrome.alarms.onAlarm.addListener(async (alarm) => {
//   if (alarm.name === "awsLinkProcessor") {
//     if (isInternetStatus()) {
//       await processAndStoreAwsLinks();
//     }
//   }
// });

setInterval(async () => {
  if (isInternetStatus()) {
    await processAndStoreAwsLinks();
  }
}, 5000);

const getPopupStatus = async () => {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get("idlepopup", (result) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError); // Reject if there's an error
      } else {
        resolve(result.idlepopup || 0); // Resolve with the data or null
      }
    });
  });
};
const isIdleFromYesterday = async () => {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get("idleFromPrev", (result) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError); // Reject if there's an error
      } else {
        resolve(result.idleFromPrev || 0); // Resolve with the data or null
      }
    });
  });
};

const getIdleCount = async () => {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get("IdleTimeCount", (result) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError); // Reject if there's an error
      } else {
        resolve(result.IdleTimeCount || 0); // Resolve with the data or null
      }
    });
  });
};

// function mergeIntervals() {
//   chrome.storage.local.get(["idleIntervals", "payloadsIntervals"], (result) => {
//     let idleIntervals = result.idleIntervals || [];
//     let payloadsIntervals = result.payloadsIntervals || [];

//     // Merge idleIntervals into payloadsIntervals
//     let mergedIntervals = [...payloadsIntervals, ...idleIntervals];

//     // Update payloadsIntervals with the merged result and clear idleIntervals
//     chrome.storage.local.set(
//       {
//         payloadsIntervals: mergedIntervals,
//         idleIntervals: [],
//       },
//       () => {
//       }
//     );
//   });
// }

async function mergeIntervals() {
  try {
    const result = await new Promise((resolve) => {
      chrome.storage.local.get(["idleIntervals", "payloadsIntervals"], resolve);
    });

    let idleIntervals = result.idleIntervals || [];
    let payloadsIntervals = result.payloadsIntervals || [];

    // Merge idleIntervals into payloadsIntervals
    let mergedIntervals = [...payloadsIntervals, ...idleIntervals];

    // Update storage with merged result and clear idleIntervals
    await new Promise((resolve) => {
      chrome.storage.local.set(
        {
          payloadsIntervals: mergedIntervals,
          idleIntervals: [],
        },
        resolve
      );
    });

  } catch (error) {
    console.error("Error merging intervals:", error);
  }
}

async function transferAllIdleToActivityIntervals() {
  const db = await new Promise((resolve, reject) => {
    const request = indexedDB.open("wstracker_new_db", 1);

    request.onsuccess = function (event) {
      resolve(event.target.result);
    };

    request.onerror = function (event) {
      reject("Error opening IndexedDB: " + event.target.error);
    };
  });

  const transaction = db.transaction(
    ["idleIntervals", "activityIntervals"],
    "readwrite"
  );
  const idleStore = transaction.objectStore("idleIntervals");
  const activityStore = transaction.objectStore("activityIntervals");

  // Get all data from idleIntervals
  const idleData = await new Promise((resolve, reject) => {
    const getAllRequest = idleStore.getAll();

    getAllRequest.onsuccess = function () {
      resolve(getAllRequest.result);
    };

    getAllRequest.onerror = function (event) {
      reject("Error retrieving idleIntervals: " + event.target.error);
    };
  });

  // Loop through each entry and move to activityIntervals
  for (const data of idleData) {
    const newData = {
      startTime: data.startTime,
      endTime: data.endTime,
      data: data.data,
    };

    // Add data to activityIntervals
    await new Promise((resolve, reject) => {
      const addRequest = activityStore.add(newData);

      addRequest.onsuccess = function () {
        resolve();
      };

      addRequest.onerror = function (event) {
        reject("Error transferring data: " + event.target.error);
      };
    });
  }

  // Clear all data from idleIntervals
  await new Promise((resolve, reject) => {
    const clearRequest = idleStore.clear();

    clearRequest.onsuccess = function () {
      resolve();
    };

    clearRequest.onerror = function (event) {
      reject("Error clearing idleIntervals: " + event.target.error);
    };
  });

  //   "All idleIntervals data transferred to activityIntervals and cleared successfully."
  // );
}

let idleTime = 0;
function formatIdleTime(seconds) {
  const hours = Math.floor(seconds / 3600);
  const minutes = Math.floor((seconds % 3600) / 60);

  if (hours > 0) {
    return `${String(hours).padStart(2, "0")}hr ${String(minutes).padStart(
      2,
      "0"
    )}min`;
  } else {
    return `${String(minutes).padStart(2, "0")}min`;
  }
}

async function deleteAllIdleActivityIntervals() {
  const db = await new Promise((resolve, reject) => {
    const request = indexedDB.open("wstracker_new_db", 1);

    request.onsuccess = function (event) {
      resolve(event.target.result);
    };

    request.onerror = function (event) {
      reject("Error opening IndexedDB: " + event.target.error);
    };
  });

  const transaction = db.transaction("idleIntervals", "readwrite");
  const objectStore = transaction.objectStore("idleIntervals");

  await new Promise((resolve, reject) => {
    const clearRequest = objectStore.clear();

    clearRequest.onsuccess = function () {
      resolve();
    };

    clearRequest.onerror = function (event) {
      reject("Error deleting entries: " + event.target.error);
    };
  });
}

async function addRecord(isHandled, time, btnName) {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open("wstracker_new_db", 1);

    request.onsuccess = () => {
      const db = request.result;
      const transaction = db.transaction("idle_handled", "readwrite");
      const store = transaction.objectStore("idle_handled");

      const addRequest = store.add({ isHandled, time, btnName });

      addRequest.onsuccess = () => resolve("Record added successfully");
      addRequest.onerror = (event) =>
        reject("Error adding record: " + event.target.error);
    };

    request.onerror = (event) =>
      reject("Error opening database: " + event.target.error);
  });
}

setInterval(async () => {
  try {
    let status = await getPopupStatus();
    idleTime = await getIdleCount();
    timestring = formatIdleTime(idleTime * 60);
    if (status == 1) {
      document.getElementById("idlediv").style.display = "block";
      document.getElementById("popupWindow").style.filter = "blur(0.2px)";
      document.getElementById("popupWindow").style.opacity = "0.5";
      document.getElementById("popupWindow").style.pointerEvents = "none";
      document.getElementById("idletext").innerHTML = timestring;
    } else {
      document.getElementById("idlediv").style.display = "none";
      document.getElementById("popupWindow").style.filter = "";
      document.getElementById("popupWindow").style.opacity = "";
      document.getElementById("popupWindow").style.pointerEvents = "";
    }
  } catch (err) {
    // console.warn(err);
  }
}, 1000);

$("#stopbtn1").click(async function () {
  try {
    // debugger;
    idleTime = await getIdleCount();
    let value = document.getElementById("scales").checked;
    await addRecord(value, moment().format("YYYY-MM-DD HH:mm:ss"), "continue");
    value = value == true ? 1 : 0;

    if (value == 0) {
      chrome.storage.local.set({ idleIntervals: [] });
      chrome.storage.local.set({ subtractBoolean: 1 });
      let val = await isIdleFromYesterday();
      if (val == 1) {
        let time = moment().format("YYYY-MM-DD HH:mm:ss");
        let parsedTime = moment(time, "YYYY-MM-DD HH:mm:ss");
        let secondsSinceMidnight = parsedTime.diff(
          moment().startOf("day"),
          "seconds"
        );

        await updateIdleTime(secondsSinceMidnight);
        chrome.storage.local.set({ idleFromPrev: 0 });
      } else {
        await updateIdleTime(idleTime * 60);
      }
      await deleteAllIdleActivityIntervals();
    } else {
      await mergeIntervals();
      await transferAllIdleToActivityIntervals();
    }
    chrome.storage.local.set({ idlepopup: 0 });
    chrome.storage.local.set({ subtractTimer: idleTime });

    chrome.storage.local.set({ IdleTimeCount: 0 });
  } catch (err) {
    await addLog(err, moment().format("YYYY-MM-DD HH:mm:ss"));
  }
});

$("#stopbtn2").click(async function () {
  try {
    idleTime = await getIdleCount();
    let value = document.getElementById("scales").checked;
    value = value == true ? 1 : 0;
    await addRecord(value, moment().format("YYYY-MM-DD HH:mm:ss"), "stop");
    if (value == 0) {
      chrome.storage.local.set({ idleIntervals: [] });
      chrome.storage.local.set({ subtractBoolean: 1 });
      chrome.storage.local.set({ nhikrna: 1 });
      let val = await isIdleFromYesterday();
      if (val == 1) {
        let time = moment().format("YYYY-MM-DD HH:mm:ss");
        let parsedTime = moment(time, "YYYY-MM-DD HH:mm:ss");
        let secondsSinceMidnight = parsedTime.diff(
          moment().startOf("day"),
          "seconds"
        );
        await updateIdleTime(secondsSinceMidnight);
        chrome.storage.local.set({ idleFromPrev: 0 });
      } else {
        await updateIdleTime(idleTime * 60);
      }
      await deleteAllIdleActivityIntervals();
    } else {
      await mergeIntervals();
      await transferAllIdleToActivityIntervals();
    }
    chrome.storage.local.set({ idlepopup: 0 });
    chrome.storage.local.set({ subtractTimer: idleTime });

    // reset...
    chrome.storage.local.set({ IdleTimeCount: 0 });
    chrome.storage.local.set({ isIdle: true });
  } catch (err) {
    await addLog(err, moment().format("YYYY-MM-DD HH:mm:ss"));
  }
});

const moveToHome = async () => {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get("setuserlogout", (result) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError); // Reject if there's an error
      } else {
        resolve(result.setuserlogout || 0); // Resolve with the data or null
      }
    });
  });
};

const checkToStopTimer = async () => {
  return new Promise((resolve, reject) => {
    chrome.storage.local.get("stopTimer", (result) => {
      if (chrome.runtime.lastError) {
        reject(chrome.runtime.lastError); // Reject if there's an error
      } else {
        resolve(result.stopTimer || 0); // Resolve with the data or null
      }
    });
  });
};

setInterval(async () => {
  let val = await moveToHome();
  if (val == 1) {
    chrome.storage.local.set({ setuserlogout: 0 });
    await stopTimerNow();
    window.location.href = "logout.html";
  }
}, 1000);

setInterval(async () => {
  let val = await checkToStopTimer();
  if (val == 1) {
    chrome.storage.local.set({ stopTimer: 0 });
    chrome.storage.local.set({ idleIntervals: [] });
    chrome.storage.local.set({ subtractBoolean: 1 });
    document.getElementById("idlediv").style.display = "none";
    document.getElementById("popupWindow").style.filter = "";
    document.getElementById("popupWindow").style.opacity = "";
    document.getElementById("popupWindow").style.pointerEvents = "";
    await deleteAllIdleActivityIntervals();
    let val = await isIdleFromYesterday();
    if (val == 1) {
      let currentTimeSec = moment().unix();
      await updateIdleTime(currentTimeSec);
      chrome.storage.local.set({ idleFromPrev: 0 });
    } else {
      await updateIdleTime(idleTime * 60);
    }
    chrome.storage.local.set({ idlepopup: 0 });
    chrome.storage.local.set({ subtractTimer: idleTime });

    chrome.storage.local.set({ IdleTimeCount: 0 });
    await stopTimerNow();
  }
}, 1000);
