import { app, Menu, BrowserWindow, dialog, nativeImage, shell } from "electron";
import { ElectronBlocker } from "@ghostery/adblocker-electron";
import { getValue } from "./config/store.js";
import { dirname, join } from "path";
import { fileURLToPath } from "url";

app.commandLine.appendSwitch('in-process-gpu')

import { getScreenWidth, getScreenHeight } from "./config/dimensions.js";
import WindowsChrome from "./useragents.json" with { type: "json" }
import checkInternetConnected from "check-internet-connected";
import domains from "./domains.json" with { type: "json" };
import contextMenu from "electron-context-menu";
import menulayout from "./config/menu.js";
import logpkg from "electron-log";

const { transports, log: _log, functions } = logpkg;
const __filename = fileURLToPath(import.meta.url);
const windowHeight = getValue("windowHeight");
const windowWidth = getValue("windowWidth");
const __dirname = dirname(__filename);
export const appUrl = `https://akartonbv.sharepoint.com/:x:/r/sites/Bedrijfsbureau/Gedeelde%20documenten/Productieplanning%20OneDrive.xlsx?d=w818e118382dd4d1cab1ddf4d505daa9e&csf=1&web=1&e=zE73Rr`
//https://akartonbv.sharepoint.com/:x:/r/sites/Bedrijfsbureau/Gedeelde%20documenten/Productieplanning%20OneDrive.xlsx?d=w818e118382dd4d1cab1ddf4d505daa9e&csf=1&web=1&e=zE73Rr

transports.file.level = "verbose";
console.log = _log;
Object.assign(console, functions);

function createWindow() {
  const partition = "persist:work";

  const win = new BrowserWindow({
    width: Math.round(getScreenWidth() * getValue("windowWidth")),
    height: Math.round(getScreenHeight() * getValue("windowHeight")),
    icon: join(__dirname, "/assets/icons/png/1024x1024.png"),
    show: false,
    webPreferences: {
      nodeIntegration: true,
      devTools: true,
      partition: partition,
    },
  });

  win.webContents.session.on('will-download', (event, item) => {
    event.preventDefault(); // Blocks the download entirely
    console.log(`Blocked download attempt: ${item.getURL()}`);
  });

  win.setAutoHideMenuBar(getValue("autohide-menubar") === "true");

  const splash = new BrowserWindow({
    width: Math.round(getScreenWidth() * 0.49),
    height: Math.round(getScreenHeight() * 0.65),
    transparent: true,
    frame: false,
    icon: join(__dirname, "/assets/icons/png/1024x1024.png"),
  });

  // Careful, this loading animation relies fully on that page.
  splash.loadURL(`https://agam778.github.io/MS-365-Electron/loading`);

  //The following line is regarding the starting page.
  //The default is: https://microsoft365.com/${custompage}/${enterpriseOrNormal}
  win.loadURL(appUrl, {
    userAgent: getValue("useragentstring") || WindowsChrome,
  });

  win.webContents.on("did-finish-load", () => {
    splash.destroy();
    win.show();
    if (getValue("blockadsandtrackers") === "true") {
      ElectronBlocker.fromPrebuiltAdsAndTracking(fetch).then((blocker) => {
        try { // Only enable if not already enabled
          blocker.enableBlockingInSession(win.webContents.session);
        } catch (e) {
          console.warn("Adblocker already enabled for this session");
        }
      }).catch(console.error);
    }
  });
}

app.on("web-contents-created", (event, contents) => {
  contents.setWindowOpenHandler(({ url }) => {
    const urlObject = new URL(url);
    const domain = urlObject.hostname;
    const protocol = urlObject.protocol;

    if (getValue("externalLinks") === "true") {
      if (protocol === "http:" || protocol === "https:") {
        const isAllowedDomain = domains.domains.some((allowedDomain) =>
          new RegExp(`^${allowedDomain.replace("*.", ".*")}$`).test(domain)
        );

        if (isAllowedDomain) {
          if (getValue("websites-in-new-window") === "false") {
            if (url.includes("page=Download")) return { action: "allow" };
            BrowserWindow.getFocusedWindow().loadURL(url).catch();
            return { action: "deny" };
          } else {
            return {
              action: "allow",
              overrideBrowserWindowOptions: {
                width: Math.round(getScreenWidth() * (windowWidth - 0.07)),
                height: Math.round(getScreenHeight() * (windowHeight - 0.07)),
              },
            };
          }
        } else {
          shell.openExternal(url);
          return { action: "deny" };
        }
      } else {
        return { action: "deny" };
      }
    } else {
      if (getValue("websites-in-new-window") === "false") {
        if (url.includes("page=Download")) return { action: "allow" };
        BrowserWindow.getFocusedWindow().loadURL(url).catch();
        return { action: "deny" };
      } else {
        return {
          action: "allow",
          overrideBrowserWindowOptions: {
            width: Math.round(getScreenWidth() * (windowWidth - 0.07)),
            height: Math.round(getScreenHeight() * (windowHeight - 0.07)),
          },
        };
      }
    }
  });
  contents.on("did-finish-load", () => {
    if (getValue("dynamicicons") === "true") {
      if (BrowserWindow.getFocusedWindow()) {
        if (
          BrowserWindow.getFocusedWindow().webContents.getURL().includes("&ithint=file%2cpptx") ||
          BrowserWindow.getFocusedWindow().webContents.getTitle().includes(".pptx")
        ) {
          if (process.platform === "darwin") {
            app.dock.setIcon(join(__dirname, "../assets/icons/apps/powerpoint-mac.png"));
          } else if (process.platform === "win32") {
            let nimage = nativeImage.createFromPath(
              join(__dirname, "../assets/icons/apps/powerpoint.png")
            );
            BrowserWindow.getAllWindows().forEach((window) => {
              window.setOverlayIcon(nimage, "PowerPoint");
            });
          }
        } else if (
          BrowserWindow.getFocusedWindow().webContents.getURL().includes("&ithint=file%2cdocx") ||
          BrowserWindow.getFocusedWindow().webContents.getTitle().includes(".docx")
        ) {
          if (process.platform === "darwin") {
            app.dock.setIcon(join(__dirname, "../assets/icons/apps/word-mac.png"));
          } else if (process.platform === "win32") {
            let nimage = nativeImage.createFromPath(
              join(__dirname, "../assets/icons/apps/word.png")
            );
            BrowserWindow.getAllWindows().forEach((window) => {
              window.setOverlayIcon(nimage, "Word");
            });
          }
        } else if (
          BrowserWindow.getFocusedWindow().webContents.getURL().includes("&ithint=file%2cxlsx") ||
          BrowserWindow.getFocusedWindow().webContents.getTitle().includes(".xlsx")
        ) {
          if (process.platform === "darwin") {
            app.dock.setIcon(join(__dirname, "../assets/icons/apps/excel-mac.png"));
          } else if (process.platform === "win32") {
            let nimage = nativeImage.createFromPath(
              join(__dirname, "../assets/icons/apps/excel.png")
            );
            BrowserWindow.getAllWindows().forEach((window) => {
              window.setOverlayIcon(nimage, "Excel");
            });
          }
        } else if (
          BrowserWindow.getFocusedWindow().webContents.getURL().includes("outlook.live.com") ||
          BrowserWindow.getFocusedWindow().webContents.getURL().includes("outlook.office.com")
        ) {
          if (process.platform === "darwin") {
            app.dock.setIcon(join(__dirname, "../assets/icons/apps/outlook-mac.png"));
          } else if (process.platform === "win32") {
            let nimage = nativeImage.createFromPath(
              join(__dirname, "../assets/icons/apps/outlook.png")
            );
            BrowserWindow.getAllWindows().forEach((window) => {
              window.setOverlayIcon(nimage, "Outlook");
            });
          }
        } else if (
          BrowserWindow.getFocusedWindow().webContents.getURL().includes("onedrive.live.com") ||
          BrowserWindow.getFocusedWindow().webContents.getURL().includes("onedrive.aspx")
        ) {
          if (process.platform === "darwin") {
            app.dock.setIcon(join(__dirname, "../assets/icons/apps/onedrive-mac.png"));
          } else if (process.platform === "win32") {
            let nimage = nativeImage.createFromPath(
              join(__dirname, "../assets/icons/apps/onedrive.png")
            );
            BrowserWindow.getAllWindows().forEach((window) => {
              window.setOverlayIcon(nimage, "OneDrive");
            });
          }
        } else if (
          BrowserWindow.getFocusedWindow().webContents.getURL().includes("teams.live.com")
        ) {
          if (process.platform === "darwin") {
            app.dock.setIcon(join(__dirname, "../assets/icons/apps/teams-mac.png"));
          } else if (process.platform === "win32") {
            let nimage = nativeImage.createFromPath(
              join(__dirname, "../assets/icons/apps/teams.png")
            );
            BrowserWindow.getAllWindows().forEach((window) => {
              window.setOverlayIcon(nimage, "Teams");
            });
          }
        } else if (
          BrowserWindow.getFocusedWindow().webContents.getURL().includes("&ithint=onenote")
        ) {
          if (process.platform === "darwin") {
            app.dock.setIcon(join(__dirname, "../assets/icons/apps/onenote-mac.png"));
          } else if (process.platform === "win32") {
            let nimage = nativeImage.createFromPath(
              join(__dirname, "../assets/icons/apps/onenote.png")
            );
            BrowserWindow.getAllWindows().forEach((window) => {
              window.setOverlayIcon(nimage, "OneNote");
            });
          }
        } else {
          if (process.platform === "darwin") {
            app.dock.setIcon(null);
          } else {
            BrowserWindow.getAllWindows().forEach((window) => {
              window.setOverlayIcon(null, "");
            });
          }
        }
      }
    }
    BrowserWindow.getAllWindows().forEach((window) => {
      if (window.webContents.getURL().includes("outlook.live.com")) {
        window.webContents
          .executeJavaScript(
            `
            const observer = new MutationObserver((mutationsList) => {
              let adElementFound = false;
              for (const mutation of mutationsList) {
                if (mutation.type === 'childList') {
                  const adElement = document.querySelector('div.GssDD');
                  if (adElement) {
                    adElement.remove();
                    adElementFound = true;
                  }
                }
              }
              if (adElementFound) {
                observer.disconnect();
              }
            });

            observer.observe(document.body, { childList: true, subtree: true });

            const adElement = document.querySelector('div.GssDD');
            if (adElement) {
              adElement.remove();
              observer.disconnect();
            }
            `
          )
          .catch();
      }
    });
    contents.insertCSS(
      `
      ::-webkit-scrollbar {
        width: 8px;
        height: 8px;
      }

      ::-webkit-scrollbar-track {
        background: transparent;
      }

      ::-webkit-scrollbar-thumb {
        background: transparent;
        border-radius: 5px;
      }

      ::-webkit-scrollbar-thumb:hover {
        background: #555;
      }      
      `
    );
  });
});

app.on("browser-window-created", (event, window) => {
  if (getValue("autohide-menubar") === "true") {
    window.setAutoHideMenuBar(true);
  } else {
    window.setAutoHideMenuBar(false);
  }
  if (getValue("blockadsandtrackers") === "true") {
    ElectronBlocker.fromPrebuiltAdsAndTracking(fetch).then((blocker) => {
      // Only enable if not already enabled
      try {
        blocker.enableBlockingInSession(win.webContents.session);
      } catch (e) {
        console.warn("Adblocker already enabled for this session");
      }
    }).catch(console.error);
  }
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
  if (process.platform === "darwin") {
    app.dock.setIcon(null);
  }
});

app.on("activate", () => {
  if (BrowserWindow.getAllWindows().length === 0) {
    createWindow();
  }
});

app.on("ready", function () {
  checkInternetConnected().catch(() => {
    const options = {
      type: "warning",
      buttons: ["Ok"],
      defaultId: 2,
      title: "Warning",
      message: "You appear to be offline!",
      detail:
        "Please check your Internet Connectivity. This app cannot run without an Internet Connection!",
    };
    dialog.showMessageBox(null, options, (response) => {
      console.log(response);
    });
  });
});

contextMenu({
  showInspectElement: false,
  showServices: false,
});

Menu.setApplicationMenu(Menu.buildFromTemplate(menulayout));

app.on("ready", () => {
  createWindow();
});
