const { ipcMain } = require('electron')
const { app, BrowserWindow } = require('electron')
const { ArgumentParser } = require('argparse')
const path = require('path')

const { Config, from_cli_parser } = require('./src/config.js')

const arguments = (() => {
	const parser = new ArgumentParser({
		description: 'Freechat client'
	})
	parser.add_argument('-c', '--config', {help: 'Specify config path'})
	return parser
})()


let win
let config = from_cli_parser(arguments)

// NOTE: this line is only here for demonstration as the current make script exposes this var
// so that we can test against self signed certificates but still use ssl
// process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = '0'

function createWin() {
	win = new BrowserWindow({
		width: 800,
		height: 600,
		minWidth: 640,
		minHeight: 480,
		webPreferences: {
			nodeIntegration: true,
			preload: path.join(__dirname + '/preload.js')
		},
		autoHideMenuBar: true,
	})

	win.loadFile('pages/index.html');

	win.on('closed', () => {
		win = null
	});
}


app.on('ready', createWin);

// on mac just because the windows are closed doesn't mean the application is too
// ! The toolbar keeps things alive against its will
app.on('window-all-closed', () => {
	if(process.platform !== 'darwin') {
		app.quit()
	}
});

app.on('activate', () => {
	if(win === null) {
		createWin();
		load_config('./example-dev-config.json'); // for now
	}
});

// returns the in-memory config reference
ipcMain.handle('config-request', async function(event, _arg) {
	return config;
})


ipcMain.handle('config-update', async function(event, updated_config) {
	config = new Config(updated_config.path, updated_config.data)
	await config.write_disk()
})

