// console.log("Hello Content.js");
let INTERVAL = 600;
let keyboardEvents = [];
let mouseEvents = [];
let keyboardCount = 0;
let mouseMoveCount = 0;
let mouseClickCount = 0;
let keyboardActivityArray = new Array(INTERVAL).fill(false); // Track keyboard activity for 600 seconds
let mouseActivityArray = new Array(INTERVAL).fill(false); // Track mouse activity for 600 seconds
let prevMouseX = 0,
  prevMouseY = 0;
let idleThresholdSeconds = 180; // Idle threshold in seconds
let keyboardWeight = 0.6;
let mouseWeight = 0.4;

let isIdle = true;
let idleCount = 0;

// setInterval(() => {
//   console.log(isIdle);
//   if (isIdle == true) {
//     idleCount++;
//     if (idleCount >= 60) {
//       chrome.runtime.sendMessage(
//         { action: "yesidle", data: isIdle },
//         (response) => {
//           console.log("Response from background:", response);
//         }
//       );
//       idleCount = 0;
//     }
//   } else {
//     isIdle = true;
//     idleCount = 0;
//   }
// }, 1000);

// content.js

chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  // console.log("Data received from background.js:", message);
  const { timeInterval } = message;
  // console.log(timeInterval);
  INTERVAL = timeInterval;
  keyboardActivityArray = new Array(INTERVAL).fill(false);
  mouseActivityArray = new Array(INTERVAL).fill(false);
  sendResponse({ status: "Data received successfully" });
});

// Set up event listeners for keyboard and mouse
document.addEventListener("keydown", onKeyPress);
document.addEventListener("mousemove", onMouseMove);
document.addEventListener("click", onMouseClick);
document.addEventListener("wheel", onMouseScroll);

// Handle mouse click event
function onMouseClick(event) {
  isIdle = false;
  let currentTime = Date.now();
  let secondIndex = Math.floor((currentTime / 1000) % INTERVAL);
  mouseClickCount++;
  mouseEvents.push({
    time: new Date(currentTime).toISOString(),
    action: `Mouse clicked at (${event.clientX}, ${event.clientY}) with ${event.button}`,
  });
  mouseActivityArray[secondIndex] = true; // Mark mouse activity
  chrome.storage.local.get("globalActivityData", (result) => {
    const globalActivityData = result.globalActivityData || {};
    globalActivityData.mouseClickCount =
      (globalActivityData.mouseClickCount || 0) + 1;

    // Merge mouse activity array
    if (!globalActivityData.mouseActivityArray) {
      globalActivityData.mouseActivityArray = new Array(INTERVAL).fill(false);
    }
    for (let i = 0; i < INTERVAL; i++) {
      globalActivityData.mouseActivityArray[i] =
        globalActivityData.mouseActivityArray[i] || mouseActivityArray[i];
    }

    chrome.storage.local.set({ globalActivityData: globalActivityData }, () => {
      // // console.log(
      //   "mouseClickCount updated:",
      //   globalActivityData.mouseClickCount,
      //   mouseActivityArray
      // );
    });
  });
}

// Handle mouse scroll event
function onMouseScroll(event) {
  isIdle = false;
  let currentTime = Date.now();
  let secondIndex = Math.floor((currentTime / 1000) % INTERVAL);
  mouseMoveCount++;
  mouseActivityArray[secondIndex] = true; // Mark mouse activity
  chrome.storage.local.get("globalActivityData", (result) => {
    const globalActivityData = result.globalActivityData || {};
    globalActivityData.mouseMoveCount =
      (globalActivityData.mouseMoveCount || 0) + 1;

    // Merge mouse activity array
    if (!globalActivityData.mouseActivityArray) {
      globalActivityData.mouseActivityArray = new Array(INTERVAL).fill(false);
    }
    for (let i = 0; i < INTERVAL; i++) {
      globalActivityData.mouseActivityArray[i] =
        globalActivityData.mouseActivityArray[i] || mouseActivityArray[i];
    }

    chrome.storage.local.set({ globalActivityData: globalActivityData }, () => {
      // console.log(
      //   "Mouse Scroll updated:",
      //   globalActivityData.mouseActivityArray,
      //   mouseActivityArray
      // );
    });
  });
}

// Handle mouse move event
function onMouseMove(event) {
  isIdle = false;
  let moveDistance = Math.sqrt(
    Math.pow(event.clientX - prevMouseX, 2) +
      Math.pow(event.clientY - prevMouseY, 2)
  );
  if (moveDistance < 5) {
    mouseMoveCount += 0.5;
  } else {
    mouseMoveCount++;
  }
  let currentTime = Date.now();
  let secondIndex = Math.floor((currentTime / 1000) % INTERVAL);
  mouseActivityArray[secondIndex] = true; // Mark mouse activity
  prevMouseX = event.clientX;
  prevMouseY = event.clientY;
  chrome.storage.local.get("globalActivityData", (result) => {
    const globalActivityData = result.globalActivityData || {};
    globalActivityData.mouseMoveCount =
      (globalActivityData.mouseMoveCount || 0) + 1;

    // Merge the old and new mouse activity arrays
    if (!globalActivityData.mouseActivityArray) {
      globalActivityData.mouseActivityArray = new Array(INTERVAL).fill(false);
    }
    for (let i = 0; i < INTERVAL; i++) {
      globalActivityData.mouseActivityArray[i] =
        globalActivityData.mouseActivityArray[i] || mouseActivityArray[i];
    }

    chrome.storage.local.set({ globalActivityData: globalActivityData }, () => {
      // console.log(
      //   "mouseMoveCount updated:",
      //   globalActivityData.mouseMoveCount,
      //   mouseActivityArray
      // );
    });
  });
}

// Handle keyboard press event
function onKeyPress(event) {
  isIdle = false;
  let currentTime = Date.now();
  let secondIndex = Math.floor((currentTime / 1000) % INTERVAL);
  keyboardCount++;
  keyboardEvents.push({
    time: new Date(currentTime).toISOString(),
    action: `Key pressed: ${event.key}`,
  });
  keyboardActivityArray[secondIndex] = true; // Mark keyboard activity
  chrome.storage.local.get("globalActivityData", (result) => {
    const globalActivityData = result.globalActivityData || {};
    globalActivityData.keyboardCount =
      (globalActivityData.keyboardCount || 0) + 1;

    // Merge the old and new keyboard activity arrays
    if (!globalActivityData.keyboardActivityArray) {
      globalActivityData.keyboardActivityArray = new Array(INTERVAL).fill(
        false
      );
    }
    for (let i = 0; i < INTERVAL; i++) {
      globalActivityData.keyboardActivityArray[i] =
        globalActivityData.keyboardActivityArray[i] || keyboardActivityArray[i];
    }

    chrome.storage.local.set({ globalActivityData: globalActivityData }, () => {
      // console.log(
      //   "keyboardCount updated:",
      //   globalActivityData.keyboardCount,
      //   keyboardActivityArray
      // );
    });
  });
}
//Getting Payload From Background.js
// chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
//   console.log(message.data);
// });

// // Listen for messages from the background script
// chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
//   if (message.type === "ERROR") {
//     // Handle the error message
//     console.error("Received error from background script:", message.message);

//     // Optionally display the error in the content page (e.g., in a div or alert)
//     alert(`Error from background script: ${message.message}`);

//     // Respond back if needed
//     sendResponse({ status: "error received" });
//   }
// });
// Function to apply blur to an image

// function applyBlurToImage(imageDataUrl) {
//   return new Promise((resolve, reject) => {
//     const img = new Image();
//     img.crossOrigin = "anonymous"; // Handle cross-origin issues if needed
//     img.src = imageDataUrl;

//     img.onload = () => {
//       const canvas = document.createElement("canvas");
//       const ctx = canvas.getContext("2d");

//       // Set canvas dimensions
//       canvas.width = img.width;
//       canvas.height = img.height;

//       // Draw the image on the canvas
//       ctx.drawImage(img, 0, 0);

//       // Apply blur filter
//       ctx.filter = "blur(5px)"; // Adjust the blur intensity as needed
//       ctx.drawImage(canvas, 0, 0);

//       // Get the blurred image as base64
//       const blurredImageDataUrl = canvas.toDataURL("image/png");
//       resolve(blurredImageDataUrl);
//     };

//     img.onerror = (error) => {
//       reject(`Error loading image: ${error}`);
//     };
//   });
// }

// // Listener for messages from the background script
// chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
//   if (message.type === "APPLY_BLUR") {
//     console.log("Received image data to blur from background script.");
//     applyBlurToImage(message.data)
//       .then((blurredImage) => {
//         console.log("Blurred image created.");
//         console.log(blurredImage);
//         sendResponse({ blurredImage });
//       })
//       .catch((error) => {
//         console.error("Error applying blur:", error);
//         sendResponse({ error });
//       });

//     // Return true to indicate the response will be sent asynchronously
//     return true;
//   }
// });

// common.js

// chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
//   if (message.action === "processData") {
//     const data = message.data;

//     let modifiedData = await applyBlurInBackground(data);
//     const processedData = {
//       status: "Image processed successfully",
//       imageDataUrl: modifiedData,
//     };
//     console.log(processedData);

//     // Send the modified data back to the background script
//     sendResponse(processedData);

//     // Indicate that the response will be sent asynchronously if needed
//     return true;
//   }
// });

// -------------------SCREENSHOT CODE---------------------

function isInternetStatus() {
  return navigator.onLine;
}

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);
    }
  });
}

//++++++++++++++++++++++++++++++++++++++++++++++++++++++





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 {
          // console.log("Upload successful:", data);
          resolve(data);
        }
      });
    });
  } catch (error) {
    console.error("Error during S3 upload:", error);
    return null; // Return null if an exception occurs
  }
}

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 });
  // console.log("Processed links moved to awsLink and removed from SSLink.");
}

chrome.runtime.onMessage.addListener(async (request, sender, sendResponse) => {
  try {
    if (request.message === "awsTrigger") {
      if (isInternetStatus()) {
        await processAndStoreAwsLinks();
      }
    }
  } catch (e) {
    // console.log(e);
  }
  return true;
});
