import { app, BrowserWindow } from "electron";
import fs from 'fs/promises'
import { WORKING_DIR } from "../constants";
import path from "path";
import { Logger } from "../logger";

const logger = Logger('bootloader');

/**
 * Boot функция, эта функция запускает приложение
 * @param window окно
 */
export async function boot(window : BrowserWindow) {
    if (!app.isPackaged && process.env['ELECTRON_RENDERER_URL']) {
        await bootDevelopment(window);
       // await bootProduction(window);
        window.webContents.openDevTools({ mode: 'detach' });
        //console.info(window.webContents);
        return;
    }
    //window.webContents.openDevTools({ mode: 'detach' });
    await bootProduction(window);
}

async function bootProduction(window : BrowserWindow) {
    logger.log("Booting in production mode");
    let html = path.join(WORKING_DIR, 'b', 'j.html');
    if(await existsFile(html)){
        logger.log(`Loading compiled file`);
        window.loadFile(html);
    } else {
        logger.log(`Loading conatiner file`);
        window.loadFile(path.join(__dirname, '../renderer/dev.html'));
    }
}

async function bootDevelopment(window : BrowserWindow) {
    logger.log("Booting in development mode");
	window.loadURL(process.env['ELECTRON_RENDERER_URL'] + "/dev.html");
	window.webContents.openDevTools({ mode: 'detach' });
}

async function existsFile(filePath: string): Promise<boolean> {
    try {
        await fs.access(filePath);
        return true;
    } catch {
        return false;
    }
}
