import { app, shell, BrowserWindow } from 'electron';
import { join } from 'path';
import { electronApp, optimizer, is } from '@electron-toolkit/utils';
import icon from '../../resources/icon.png?asset';
import serve from 'electron-serve';
import windowStateManager from 'electron-window-state';

import './lib/utils';
import { addCacheHandling } from './lib/cache';

const serveURL = serve({
	directory: join(__dirname, '..', 'renderer'),
	scheme: 'eve'
});

let mainWindow: BrowserWindow;
function createWindow(): void {
	const windowState = windowStateManager({
		defaultWidth: 1366,
		defaultHeight: 768
	});

	mainWindow = new BrowserWindow({
		width: windowState.width,
		height: windowState.height,
		x: windowState.x,
		y: windowState.y,
		show: false,
		fullscreen: true,
		autoHideMenuBar: true,
		icon,
		webPreferences: {
			preload: join(__dirname, '../preload/index.js'),
			sandbox: false
		}
	});

	windowState.manage(mainWindow);
	mainWindow.on('close', () => {
		windowState.saveState(mainWindow);
	});

	mainWindow.on('ready-to-show', () => {
		mainWindow.show();
	});

	mainWindow.webContents.setWindowOpenHandler((details) => {
		shell.openExternal(details.url);
		return { action: 'deny' };
	});
	if (is.dev) {
		loadVite();
		mainWindow.webContents.openDevTools();
	} else serveURL(mainWindow);
}

function loadVite(): void {
	mainWindow.loadURL(import.meta.env.MAIN_VITE_ELECTRON_RENDERER_URL).catch((e) => {
		console.log('Error loading URL, retrying', e);
		setTimeout(() => {
			loadVite();
		}, 200);
	});
}

app.whenReady().then(() => {
	electronApp.setAppUserModelId('com.arx-ccn');

	addCacheHandling();

	app.on('browser-window-created', (_, window) => {
		optimizer.watchWindowShortcuts(window);
	});

	createWindow();
});
