const { BrowserWindow, app, net, dialog, ipcMain } = require("electron")
const os = require("os")
const hwid = require("./modules/hwid")
const path = require("node:path")
const config = require("./config.json")
let launcherWindow

async function createLauncherWindow() {
    if (net.isOnline()) {
        const isLauncherNotBanned = await checkIfIAmBanned()
        launcherWindow = new BrowserWindow({
            frame: false,
            width: 900,
            height: 600,
            minWidth: 900,
            minHeight: 600,
            titleBarStyle: "hidden",
            autoHideMenuBar: true,
            roundedCorners: false,
            resizable: false,
            webPreferences: {
                nodeIntegration: false,
                contextIsolation: true,
                preload: path.join(__dirname, "app", "index.html")
            }
        })
        if (isLauncherNotBanned.success) {
            launcherWindow.loadFile(path.join(__dirname, "app", "index.html"))
        } else {
            launcherWindow.loadFile(path.join(__dirname, "app", "banned.html"))
            launcherWindow.webContents.executeJavaScript(`
                setBannedBy("${isLauncherNotBanned.banned_by}")
                setBannedAt("${isLauncherNotBanned.banned_at}")
                setBannedBecause("${isLauncherNotBanned.reason}")
            `)
        }
    } else {
        dialog.showErrorBox("Le launcher requiert une connexion internet.")
    }
}

async function checkIfIAmBanned() {
    if (net.isOnline()) {
        try {
            const reponse = await fetch(config, {
                body: JSON.stringify({
                    hwid: hwid.getHWID()
                })
            })   
            const json = await reponse.json()
            return json
        } catch (error) {
            dialog.showErrorBox("Impossible de contacter l'API, fermeture du launcher.")
            console.error(error)
            app.exit()
        }
    } else {
        dialog.showErrorBox("Le launcher requiert une connexion internet.")
    }
}

app.whenReady().then(() => {
    createLauncherWindow()
    app.on("activate", async () => {
        if (BrowserWindow.getAllWindows().length === 0) await createLauncherWindow()
    })
})

app.on("window-all-closed", () => {
    app.quit()
})

ipcMain.on("call", (event, data) => {
    switch (data.method) {
        case "hardware::ramInformation":
            launcherWindow.webContents.send("hardware::ramInformation", {
                totalRam: Math.round(os.totalmem() / 1024 / 1024 * 100) / 100,
                avaibleRam: Math.round(os.freemem() / 1024 / 1024 * 100) / 100,
            })
            break
    }
})