let { BrowserWindow } = require('electron');
const log = require('electron-log');

if (!BrowserWindow) {
    BrowserWindow = require('@electron/remote').BrowserWindow;
}

const getByNameOrId = (nameOrId, allWindows) => {
    const keyType = typeof nameOrId;

    if (keyType !== 'string' && keyType !== 'number') {
        log.warn('[neuroAd] break find getAppWindow() - key not string or number');

        return null;
    }

    const result = allWindows.find((win) => {
        const { id, name } = win?.webContents?.browserWindowOptions || {};

        if (id === nameOrId || name === nameOrId) {
            return true;
        }
    });

    return (result || null);
};

module.exports = (stringNameOrNumberId = null) => {
    try {
        const allWindows = BrowserWindow?.getAllWindows();

        // log.debug('[neuroAd] getAppWindow() windows length:', allWindows.length);

        if (!Array.isArray(allWindows) || allWindows.length === 0) {
            log.warn('[neuroAd] break getAppWindow() not found any app windows');

            return null;
        }

        if (stringNameOrNumberId || stringNameOrNumberId === 0) {
            return getByNameOrId(stringNameOrNumberId, allWindows);
        }

        return allWindows[0];
    } catch (err) {
        log.error('mod:getAppWindow', err);
    }
};