const { app, BrowserWindow, Menu, globalShortcut } = require('electron')

// 在主进程中
const fs = require('fs').promises; // 使用 Promise 版本的 fs API
const path = require('path');

const configPath = path.join(__dirname, 'config/conf.json'); // 建议使用 path.join 构造路径


async function readConfig() {
    try {
        const data = await fs.readFile(configPath, 'utf8');
        const config = JSON.parse(data);
        return config;
    } catch (error) {
        console.error('read config file error:', error);
        // 处理错误，例如返回默认配置或抛出异常
        throw error;
    }
}

// 保持一个对于 window 对象的全局引用，
// window 会被自动地关闭
var mainWindow = null
Menu.setApplicationMenu(null);

function createWindow() {
    //当app准备好后，执行createWindow创建窗口
    mainWindow = new BrowserWindow({
        x: 0, //窗口位置x坐标
        y: 0, //窗口位置y坐标
        width: 1920, //窗口宽度
        height: 1080, //窗口高度
        title: '能源站监控与运行管理平台',
        autoHideMenuBar: true, //自动隐藏菜单档
        alwaysOnTop: false, //置顶
        show: false, // hide the window
        webPreferences: {
            partition: String(+new Date())
        },
    })

    readConfig().then((data) => {
        console.log('read CONFIG:', data);
        //加载页面
        mainWindow.loadURL(data.weburl) // 'http://127.0.0.1:19601'
    });

    mainWindow.once('ready-to-show', () => {
        mainWindow.show();
    })

    //注册Ctr+x事件
    const ret = globalShortcut.register('CommandOrControl+F12', () => {
        console.log('CommandOrControl+F12 is pressed')
        mainWindow.setFullScreen(!mainWindow.isFullScreen())
    })

    if (!ret) {
        console.log('registration failed')
    }

    // 验证是否注册成功
    console.log("regist Ctrl+F12:", globalShortcut.isRegistered('CommandOrControl+F12'))
    // app.on('activate', function () {
    //     // 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 (BrowserWindow.getAllWindows().length === 0) createWindow()
    // })
}

app.on('ready', () => { createWindow() })
app.whenReady().then();

// Quit when all windows are closed.
app.on('window-all-closed', function () {
    // Unregister a shortcut.
    globalShortcut.unregister('F12')

    // Unregister all shortcuts.
    globalShortcut.unregisterAll()
    // On macOS it is common for applications and their menu bar
    // to stay active until the user quits explicitly with Cmd + Q
    if (process.platform !== 'darwin') app.quit()
})