const { app, BrowserWindow, ipcMain, dialog } = require("electron");
const path = require("path");
const url = require("url");

const fs = require('fs')
const os = require('os');
const { error } = require("console");

let win;
function createWindow() {
	win = new BrowserWindow({
		width: 700, height: 700, webPreferences: {
			nodeIntegration: true,
			enableRemoteModule: true,
			contextIsolation: false,
			show: false
		}
	});

	// load the dist folder from Angular
	win.loadURL(
		url.format({

			// compiled version of our app
			pathname: path.join(__dirname, '/dist/index.html'),
			protocol: "file:",
			slashes: true
		})
	);
	win.on("closed", () => {
		win = null;
	});


	win.maximize();
	win.show();
}
//app.on("ready", createWindow);

app.on('ready', () => {
	createWindow();
	ipcMain.on('print', (event, args) => {
		const mainWindow = BrowserWindow.getFocusedWindow();
		
		dialog.showSaveDialog(mainWindow, { defaultPath: 'Form10B', filters: [{ name: 'PDF File', extensions: ['pdf'] }] }).then(result => {
			if (result.canceled) return
			const pdfPath = result.filePath;
			if (mainWindow) {
				mainWindow.webContents.printToPDF({ landscape: true, scale: 1, pageSize: 'A4' }).then(data => {
					fs.writeFile(pdfPath, data, (error) => {
						if (error) {
							dialog.showMessageBox(mainWindow, { message: `Failed to save PDF\r\n\r\n${error}`, type: 'error' });
							event.returnValue = "error";
						}
						else {
							dialog.showMessageBox(mainWindow, { message: 'File saved successfully!', type: 'info' });
							event.returnValue = "ok";
						}
					})
				})
			}

		})

	});
});

// If you are using MACOS, we have to quit the app manually
app.on("window-all-closed", () => {
	if (process.platform !== "darwin") {
		app.quit();
	}
});