// Created by Clayton Brown. See "LICENSE" file in root for more info.

const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;

const { spawn } = require("child_process");
const { ipcMain } = require("electron");

const path = require('path');
const isDev = require('electron-is-dev');
const findPort = require("find-free-port");

const log = require("electron-log");

let mainWindow = null;
let goPID;

async function createWindow() {

    let port = "8080"
    let key = "testKey"

    log.transports.file.level = "info";

    // First startup the go api
    if (!isDev) {

        let unpackedFolder = path.join(__dirname, "..", "..", "app.asar.unpacked")
        log.transports.file.file = path.join(unpackedFolder, "electron.log")
        findPort(8000, 9000, "127.0.0.1", (err, foundPort) => {
            log.log("Starting api on port " + foundPort)
            port = foundPort
            let goAPI = spawn("./insert-app-name-here-api", [port, key, unpackedFolder + "/"], {detached: true, cwd : path.join(unpackedFolder, "build")})
            goAPI.on("error", err => {
                log.warn(err)
            })
            goPID = goAPI.pid
        })
    } else {
        log.transports.file.file = __dirname + "/electron.log"
    }

    log.log("Starting insert-app-name-here.")

    // Set up the port getting function
    ipcMain.on("getPort", (event) => {
        event.returnValue = port
    })

    // Set up the key grabbing function
    ipcMain.on("getKey", (event) => {
        event.returnValue = key
    })

    // Create the window
    // TODO: This icon will only be loaded for ubuntu. Need to sort that out later
    mainWindow = new BrowserWindow({width: 900, height: 680, icon: path.join(__dirname, './icon.png'), webPreferences: {
        // nodeIntegration: false,
        preload: path.join(__dirname, "preload.js")
    }});

    log.log("Created browser window.")

    if (!isDev) {
        mainWindow.removeMenu();
    }

    // Wait until the site is truly loaded before doing anything
    while (true) {
        let escape = await (
            mainWindow.loadURL(isDev ? 'http://localhost:3000' : `file://${path.join(__dirname, './index.html')}`)
            .then(() => true)
            .catch(() => false)
        )
        if (escape) {
            break
        } else {
            await new Promise(res => setTimeout(res, 100))
        }
    }

    // Force a reload when complete
    mainWindow.reload()

    // Setup ready function
    ipcMain.on('isReady', event => {
        event.returnValue = true
    });

    log.log("Successfully loaded window.")

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

    // Setup fullscreen toggling
    ipcMain.on("setFullScreen", (event, arg) => {
        mainWindow.setFullScreen(arg)
        event.returnValue = "success"
    })

    // I have to do this to avoid a really weird visual bug on ubuntu 20.04. Not sure what's causing it.
    ipcMain.on("readyToGo", (event) => {
        mainWindow.setSize(1280, 720)
        event.returnValue = "success"
    })

}

app.whenReady().then(() => {
    if (mainWindow === null) {
      createWindow()
    }
})

app.on('window-all-closed', () => {
    // By quiting in all instances, darwin "macOS" apps will close completely when killed.
    app.quit();
});

app.on('activate', () => {
    if (mainWindow === null) {
      createWindow();
    }
});

app.on("before-quit", () => {
    if (!isDev)
      process.kill(goPID)
})