/*
ISC License (ISC)

Copyright 2021 James Adam Armstrong

Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above copyright
notice and this permission notice appear in all copies.

THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/

import { app, BrowserWindow } from 'electron'
import path from 'path'
import fs from 'fs'

interface Setup {
	title: string
	icon: string
	index: string
}

const defaultSetup: Readonly<Setup> = {
	title: 'LOL Calculator',
	icon: 'icon.png',
	index: 'index.html',
}

function load(name: string): Readonly<Setup> {
	try {
		const raw = fs.readFileSync(path.join(__dirname, name))
		const data = JSON.parse(raw.toString())
		if (typeof data === 'object') {
			const setup = { ...defaultSetup }
			for (const key in defaultSetup) {
				const value = data[key]
				if (typeof value === 'string') {
					setup[key] = value
				}
			}
			return setup
		} else {
			return defaultSetup
		}
	} catch (_error) {
		return defaultSetup
	}
}

function createWindow(name?: string): void {
	const { title, icon, index } = name ? load(name) : defaultSetup
	const mainWindow = new BrowserWindow({
		width: 800,
		height: 600,
		icon,
		title,
		webPreferences: {
			// preload: path.join(__dirname, 'preload.js'),
			devTools: process.env.NODE_ENV != 'production',
		},
	})
	mainWindow.menuBarVisible = false
	mainWindow.loadFile(index).then(() => mainWindow.maximize())
}

app.whenReady().then(() => {
	createWindow()
	// On macOS it's common to re-create a window in the app when the
	// dock icon is clicked and there are no other windows open.
	if (process.platform === 'darwin') {
		app.on('activate', () => {
			if (BrowserWindow.getAllWindows().length === 0) createWindow()
		})
	}
})

// 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.quit()
	}
})