const { app, BrowserWindow, ipcMain, screen } = require('electron');
const log = require('electron-log');
const path = require("path");
const fs = require("fs");

if ( !app.requestSingleInstanceLock() ) {
    app.quit();
}

app.allowRendererProcessReuse = false;

require('@electron/remote/main').initialize();

const createWindow = require('../core/createWindow.js');
const { nadInitMain } = require('../index.js');

let mainWindow = null;

//костыль для решения проблемы userData в режиме отладки
const appName = require('../../package.json').name;
app.setName(appName);

//Путь к месту запуска приложения
const appPath = process.cwd();

//Создаём при необходимости папки с данными приложения
const userData = path.join(appPath, 'data');

if (!fs.existsSync(userData)) {
    try {
        fs.mkdirSync(userData, { recursive: true });
        console.log('[info] Directory created:', userData);
    } catch (error) {
        console.error('[error] Can not create directory', userData + '. Error:', error.message);
    }
}

app.setPath('userData', userData);

app.commandLine.appendSwitch('autoplay-policy', 'no-user-gesture-required');
app.commandLine.appendSwitch('force-color-profile', 'srgb');
app.commandLine.appendSwitch('ignore-gpu-blacklist', 'true');

process.env.npm_package_dependencies_neuro_ad = 'file:node_modules/neuroAd';

const initWindow = () => {
    mainWindow = createWindow({ id: 'main' });

    mainWindow.on('closed', app.quit);

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

        nadInitMain({
            window: mainWindow,
            checkEnabling: () => true
        });
    });

    mainWindow.loadFile(path.join(__dirname, "index.html"));
};

app.once('ready', () => {
    initWindow();
});

app.on('window-all-closed', function () {
    try {
        if (process.platform !== 'darwin') {
            app.quit();
        }
    } catch (ex) {
        log.error(ex.stack);
    }
});

app.on('activate', function () {
    try {
        if (mainWindow === null) {
            initWindow();
        }
    } catch (ex) {
        log.error(ex.stack);
    }
});