const STORYONBOARDS_STORAGE_KEY = "NOTHING_BUT_SOB_STORAGE_KEY";
const STORYONBOARDS_SETTING_KEY = "NOTHING_BUT_SOB_SETTING_KEY";
const STORYONBOARDS_USER_TOKEN_KEY = "NOTHING_BUT_SOB_USER_TOKEN_KEY";

const getRandomString = (length) => {
  const alphabet = `abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789`;
  let result = "";
  for (let i = 0; i < length; i++) {
    result += alphabet[Math.floor(Math.random() * alphabet.length)];
  }
  return result;
};

chrome.sidePanel
  .setPanelBehavior({ openPanelOnActionClick: true })
  .catch((error) => console.error(error));

chrome.action.onClicked.addListener((tab) => {
  chrome.sidePanel.open({ tabId: tab.id });
});

console.log("background loaded");
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  switch (request.action) {
    case "videoShotTook":
      chrome.storage.local.get().then((values) => {
        let resources = values[STORYONBOARDS_STORAGE_KEY] || [];
        chrome.storage.local
          .set({
            [STORYONBOARDS_STORAGE_KEY]: [...resources, request.data],
          })
          .then(() => {
            console.log("Screenshot saved successfully");
          })
          .catch((err) => {
            console.error("Screenshot saved failed", err);
          });
      });

      chrome.sidePanel
        .open({ tabId: sender.tab.id })
        .then(async () => {
          sendResponse({ message: "Side panel open successfully" });
        })
        .catch((err) => {
          console.error("Side panel open failed", err);
        });
      break;
    case "closePanel":
      chrome.sidePanel.setOptions({ enabled: false });
      setTimeout(() => {
        chrome.sidePanel.setOptions({ enabled: true });
      }, 10);
      break;
    case "clearImages":
      chrome.storage.local.set({ [STORYONBOARDS_STORAGE_KEY]: [] });
      break;
    case "showLoginFrame":
      let loginWindowId = null;

      let session = getRandomString(32);

      chrome.windows.getCurrent((currentWindow) => {
        const screenWidth = currentWindow.width;
        const screenHeight = currentWindow.height;

        const popupWidth = 400;
        const popupHeight = 600;

        const top = Math.round((screenHeight - popupHeight) / 2);
        const left = Math.round((screenWidth - popupWidth) / 2);

        chrome.windows.create(
          {
            url: `${request.baseURL}?session=${session}`,
            type: "popup",
            width: popupWidth,
            height: popupHeight,
            left,
            top,
          },
          (newWindow) => {
            loginWindowId = newWindow.id;
            sendResponse({
              success: true,
              data: session,
              window: newWindow.id,
            });
          }
        );
      });

      return true;
      break;
    case "videoShotTookByBackground":
      chrome.sidePanel.open({ tabId: sender.tab.id });

      chrome.tabs.captureVisibleTab(
        sender.tab.windowId,
        { format: "jpeg" },
        (base64) => {
          sendResponse({ data: base64 });
        }
      );
      return true;
      break;
  }
});
