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

async function createLauncherWindow() {
    if (net.isOnline()) {
        let win_width = 1550
        let win_height = parseInt(win_width / (16/9))
        const isLauncherNotBanned = await checkIfIAmBanned()
        launcherWindow = new BrowserWindow({
            frame: false,
            width: win_width,
            height: win_height,
            minWidth: win_width,
            minHeight: win_height,
            titleBarStyle: "hidden",
            autoHideMenuBar: true,
            roundedCorners: false,
            resizable: false,
            webPreferences: {
                nodeIntegration: false,
                contextIsolation: true,
                preload: path.join(__dirname, "modules", "preload.html")
            }
        })
        if (isLauncherNotBanned.success) {
            launcherWindow.loadFile(path.join(__dirname, "app", "logged.html"))
        } else {
            launcherWindow.loadFile(path.join(__dirname, "app", "banned.html"))
            launcherWindow.webContents.executeJavaScript(`
                setBannedBy("${isLauncherNotBanned.banned_by}")
                setBannedAt("${isLauncherNotBanned.banned_at}")
                setBannedBecause("${isLauncherNotBanned.reason}")
            `)
        }
        if (os.platform() == "darwin") {
            app.dock.setIcon(nativeImage.createFromPath(path.join(__dirname, "app", "assets", "img", "icon.png")))
        }
        launcherWindow.setIcon(path.join(__dirname, "app", "assets", "img", "icon.png"))
    } else {
        dialog.showErrorBox("Connexion internet", "Le launcher requiert une connexion internet.")
    }
}

async function checkIfIAmBanned() {
    // if (net.isOnline()) {
    //     try {
    //         const reponse = await fetch(`${config.api.base}${config.api.endpoints.checkBanStatus}`, {
    //             method: "post",
    //             body: JSON.stringify({
    //                 hwid: hwid.getHWID()
    //             })
    //         })
    //         const json = await reponse.json()
    //         return json
    //     } catch (error) {
    //         dialog.showErrorBox("Connexion à l'API", "Impossible de contacter l'API, fermeture du launcher.")
    //         console.error(error)
    //         app.exit()
    //     }
    // } else {
    //     dialog.showErrorBox("Connexion internet", "Le launcher requiert une connexion internet.")
    // }
    return {
        success: true
    }
}

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", async (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
        case "server::ping":
            const status = await serverPing.fetchServerStatus()
            launcherWindow.webContents.send("Response<server::ping>", status)
            break
        case "window::close":
            launcherWindow.close()
            app.quit()
            break
        case "skin::set":
            const file = await dialog.showOpenDialog(launcherWindow, {
                filters: [
                    { name: "Images", extensions: ["png", "jpg", "jpeg"] }
                ],
                properties: ["openFile", "dontAddToRecent", "showHiddenFiles"],
                title: "Sélectionner l'image de votre skin",
                securityScopedBookmarks: true
            })
            if (!file.canceled) {
                skinPath = file.filePaths[0]
            }
            break
        case "skin::reset":
            skinPath = null
            break
    }
})