const {app, BrowserWindow, Menu} = require('electron')
const isDev = require('electron-is-dev');
const {TitlebarRespect} = require('electron-titlebar-respect')
const glasstron = require('glasstron-clarity');
const path = require('path')


// Use the correct icon depending on the operating system
if        /* If macOS */    (process.platform == 'darwin')  {global.AppIcon = 'public/images/icons/app/icon.icns' }
else if   /* If Windows */  (process.platform == 'win32')   {global.AppIcon = 'public/images/icons/app/icon.ico'  }
else      /* If Linux */                                    {global.AppIcon = 'public/images/icons/app/icon.png'  }


function createWindow () {
  const mainWindow = new glasstron.BrowserWindow({
    title: 'App Name',
    minWidth: 400,
    minHeight: 400,
    width: 1200,
    height: 800,
    autoHideMenuBar: true,
    show: false,
    blur: true,
    frame: global.frame,
    titleBarStyle: global.titleBarStyle,
    icon: path.join(global.AppIcon),
    trafficLightPosition: { x: 25, y: 25 }, // Position of Traffic Light buttons on macOS
    titleBarOverlay: { // Background and Height of Windows titlebar buttons
      color: '#191919', // Background
      symbolColor: 'white', // Icon
      height: '40px',
    },
    webPreferences: {
      webviewTag: true
    }
  })
  // Showing the window gracefuly
  // Doc: https://www.electronjs.org/docs/latest/api/browser-window#showing-the-window-gracefully
  mainWindow.once('ready-to-show', () => {
    mainWindow.show()
  })
  // Load Content
  if (isDev) {
    mainWindow.loadURL('http://localhost:3000') // Use a URL in development mode
  } else {
    mainWindow.loadFile('app/index.html') // Do NOT use a URL in production mode, as that can create a security risk for your customers who will use this app
  }
  // Menu
  const isMac = process.platform === 'darwin'
  const template = [
    ...(isMac ? [{
      label: app.name,
      submenu: [
        { role: 'about' },
        { type: 'separator' },
        { role: 'services' },
        { type: 'separator' },
        { role: 'hide' },
        { role: 'hideOthers' },
        { role: 'unhide' },
        { type: 'separator' },
        { role: 'quit' }
      ]
    }] : []),
    {
      label: 'File',
      submenu: [
        isMac ? { role: 'close' } : { role: 'quit' }
      ]
    },
    {
      label: 'Edit',
      submenu: [
        { role: 'undo' },
        { role: 'redo' },
        { type: 'separator' },
        { role: 'cut' },
        { role: 'copy' },
        { role: 'paste' },
        ...(isMac ? [
          { role: 'pasteAndMatchStyle' },
          { role: 'delete' },
          { role: 'selectAll' },
          { type: 'separator' },
          {
            label: 'Speech',
            submenu: [
              { role: 'startSpeaking' },
              { role: 'stopSpeaking' }
            ]
          }
        ] : [
          { role: 'delete' },
          { type: 'separator' },
          { role: 'selectAll' }
        ])
      ]
    },
    {
      label: 'View',
      submenu: [
        { role: 'reload' },
        { role: 'forceReload' },
        { role: 'toggleDevTools' },
        {
          label: 'Open WebView Developer Tools',
          accelerator: 'CmdOrCtrl+Shift+W',
          click: async () => {
              mainWindow.webContents.executeJavaScript(`document.querySelector('.active webview').openDevTools()`)
          }
        },
        { type: 'separator' },
        { role: 'resetZoom' },
        { role: 'zoomIn' },
        { role: 'zoomOut' },
        { type: 'separator' },
        { role: 'togglefullscreen' }
      ]
    },
    {
      label: 'Window',
      submenu: [
        { role: 'minimize' },
        { role: 'zoom' },
        ...(isMac ? [
          { type: 'separator' },
          { role: 'front' },
          { type: 'separator' },
          { role: 'window' }
        ] : [
          { role: 'close' }
        ])
      ]
    },
    {
      role: 'help',
      submenu: [
          {
            label: 'Learn More',
            click: async () => {
              const { shell } = require('electron')
              await shell.openExternal('https://code.korbsstudio.com/KorbsStudio/nexus-polestar')
            }
          }
      ]
    }
  ]

  const menu = Menu.buildFromTemplate(template)
  Menu.setApplicationMenu(menu)
}

// App
app.whenReady().then(() => {
  createWindow()
  // DNS
  // Doc: https://www.electronjs.org/docs/latest/api/app#appconfigurehostresolveroptions
  app.configureHostResolver({
    secureDnsMode: 'secure',
    secureDnsServers: [
      'https://cloudflare-dns.com/dns-query'
    ]
  })
})
// app.disableHardwareAcceleration()
app.on('window-all-closed', () => {
  app.quit()
})