// main.js
// const { app, BrowserWindow} = require('electron');
const { app, BrowserWindow, ipcMain, Menu } = require('electron');
const fs = require('fs');
const path = require('path');
const jquery = require('jquery');
let onlineStatus = true;
const { dialog } = require('electron');
const saveFile = require('./savexml')
require('dotenv').config({ path: path.join(__dirname, '.env') });
// const Quill = require('quill');
let mainWindow;


const auto_close= process.env.DISABLE_AUTO_CLOSE;
const auto_close_time = parseInt(process.env.AUTO_CLOSE_TIME) * 1000;

// console.assert(condition, message);


async function createWindow() {
  mainWindow = new BrowserWindow({
    width: 1200,
    height: 800,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true, //this added for paste content
      clipboard: true           ////this added for paste content
    },
  });

  // mainWindow.webContents.on('will-navigate', (event) => {
  //   mainWindow.webContents.setVisualZoomLevelLimits(5, 3);
  //   event.preventDefault();
  // });
  

   // mainWindow.removeMenu()
  mainWindow.loadFile('dashboard.html');  // Create an HTML file for your interface

  

  if(process.env.ENABLE_DEV_TOOLS === 'TRUE')
  {
    if (mainWindow) {
      mainWindow.webContents.toggleDevTools();
    }
  }
  else{
    mainWindow.webContents.on('did-finish-load', () => {
      const customMenu = buildCustomMenu();
      Menu.setApplicationMenu(customMenu);
    });
  }
  
  
  mainWindow.on('closed', function () {
    mainWindow = null;
  });

    setInterval(checkInternetConnection, 5000);

    // const divIds = ['richText', 'editor-container-2', 'editor-container-3'];
    // const editors = {};
  
    // divIds.forEach(divId => {
    //   const editor = new Quill(`.${divId}`, {
    //     theme: 'snow',
    //     // Mention and other configurations can be added here if needed
    //   });
  
    //   // Store the editors in an object or an array if you need to access them later
    //   editors[divId] = editor;
    // });
}


//Function for Remove the FrocewReload, Reload, ToggleDeveloperOption
function buildCustomMenu() {
  const template = [
    {
      label: 'File',
      submenu: [
        {
          label: 'Exit',
          click: () => app.quit(),
        },
      ],
    },
    {
      label: 'Edit',
      submenu: [
        {
          label: 'Copy',
          accelerator: 'CmdOrCtrl+C',
          click: () => {
            mainWindow.webContents.copy();
          },
        },
        {
          label: 'Cut',
          accelerator: 'CmdOrCtrl+X',
          click: () => {
            mainWindow.webContents.cut();
          },
        },
        {
          label: 'Paste',
          accelerator: 'CmdOrCtrl+V',
          click: () => {
            mainWindow.webContents.paste();
          },
        },
        {
          role: 'undo',
        },
        {
          role: 'redo',
        },
      ].filter(Boolean),
    },
    {
      label: 'View',
      submenu: [
        {
          label: 'Actual Size',
          click: () => {
            mainWindow.webContents.setZoomLevel(0);
          },
        },
        {
          label: 'Zoom In',
          click: () => {
            const currentZoomLevel = mainWindow.webContents.getZoomLevel();
            mainWindow.webContents.setZoomLevel(currentZoomLevel + 1);
          },
        },
        {
          label: 'Zoom Out',
          click: () => {
            const currentZoomLevel = mainWindow.webContents.getZoomLevel();
            mainWindow.webContents.setZoomLevel(currentZoomLevel - 1);
          },
        },
        {
          role: 'togglefullscreen',
        },
      ].filter(Boolean),
    },
    {
      label: 'Window',
      submenu: [
        {
          role: 'minimize',
        },
        {
          role: 'close',
        },
      ].filter(Boolean),
    },
    {
      label: 'Developer',
      submenu: [
        {
          label: 'Toggle Developer Tools',
          accelerator: 'CmdOrCtrl+Shift+I',
          click: () => {
            mainWindow.webContents.toggleDevTools();
          },
        },
        {
          label: 'Reload',
          accelerator: 'CmdOrCtrl+R',
          click: () => {
            mainWindow.reload();
          },
        },
      ],
    },
  ];

  return Menu.buildFromTemplate(template);
}
//End of Function for Remove the FrocewReload, Reload, ToggleDeveloperOption



async function checkInternetConnection() {
  try {
    const response = await fetch('https://www.google.com'); 
    if (response.ok && onlineStatus) {
      onlineStatus = false;
      
      if (auto_close === 'TRUE') {
       
      }else{
        dialog.showMessageBox(mainWindow, {
          type: 'info',
          message: `Internet is available. Click OK to close the app. Otherwise app will auto close in ${auto_close_time/1000} Seconds`,
          buttons: ['OK'],
        });
          //Send the tigger to AutoSave the question Paper when System come's online
          mainWindow.webContents.send('button-click');
          
        setTimeout(() => {
          app.quit();
        }, auto_close_time); 
      }
    } else if (!response.ok && !onlineStatus) {
      onlineStatus = true;
    }
  } catch (error) {
    console.error('Error checking internet connection');
  }
}


app.on('ready', createWindow);

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', function () {
  if (mainWindow === null) {
    createWindow();
  }
});
