import { app, BrowserWindow, Menu, nativeImage } from 'electron'
import { electronApp, optimizer } from '@electron-toolkit/utils'
import { createAppWindow, startApplication } from './app'
import './ipcs/ipcDatabase'
import './ipcs/ipcLogger'
import './ipcs/ipcFilestorage'
import './ipcs/ipcUpdate'
import './ipcs/ipcNotification'
import './ipcs/ipcDevice'
import { Tray } from 'electron/main'
import { join } from 'path'
import { Logger } from './logger'

let lockInstance = app.requestSingleInstanceLock();
let tray : Tray | null = null;
const size = process.platform === 'darwin' ? 18 : 22;
const logger = Logger('main');


const icon = nativeImage.createFromPath(
  join(__dirname, '../../resources/R.png')
).resize({ width: size, height: size });

if(!lockInstance){
  app.quit();
  process.exit(0);
}

process.on('unhandledRejection', (reason) => {
  logger.log(`main thread error, reason: ${reason}`);
});

app.disableHardwareAcceleration();

app.on('second-instance', () => {
  // Someone tried to run a second instance, we should focus our window.
  const allWindows = BrowserWindow.getAllWindows();
  if (allWindows.length) {
    const mainWindow = allWindows[0];
    if (mainWindow.isMinimized()) mainWindow.restore();
    if (mainWindow.isVisible() === false) mainWindow.show();
    mainWindow.focus();
  }
}); 

export const restoreApplicationAfterClickOnTrayOrDock = () => {
	const allWindows = BrowserWindow.getAllWindows();
	if (allWindows.length > 0) {
		const mainWindow = allWindows[0];
    if (mainWindow.isMinimized()){
			mainWindow.restore();
      return;
		} 
    if(mainWindow.isVisible() === false){
			mainWindow.show();
		}
		mainWindow.focus();
	} else {
		createAppWindow();
	}  
}

//Menu.setApplicationMenu(null);
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(async () => {
  electronApp.setAppUserModelId('Rosetta');
  tray = new Tray(icon);
  const contextMenu = Menu.buildFromTemplate([
    { label: 'Open App', click: () => restoreApplicationAfterClickOnTrayOrDock() },
    { label: 'Quit', click: () => app.quit() }
  ]);
  tray.setContextMenu(contextMenu);
  tray.setToolTip('Rosetta');
  tray.on('click', () => {
    restoreApplicationAfterClickOnTrayOrDock();
  });
  startApplication();

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })
 
  app.on('activate', function () {
	  restoreApplicationAfterClickOnTrayOrDock();
  });
})

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
	if (process.platform == 'darwin') {
	    app.hide();
	}
})
// In this file, you can include the rest of your app's specific main process
// code. You can also put them in separate files and import them here.
