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

const isMac = process.platform === 'darwin';
let html_page = undefined;
let mainWindow = undefined;
let alertWindow = undefined;

const createMainWindow = ((title, width, height) => {
    mainWindow = new BrowserWindow({
        title: title,
        width: width,
        height: height,
        resizable: false,
        icon: path.join(__dirname, '..', 'renderer', 'assets', 'hard-disk.png'),
        webPreferences: {
            preload: path.join(__dirname, 'preload.js')
        }
    });

    html_page = 'login.html';
    //mainWindow.setMenu(null);
    mainWindow.loadFile(path.join(__dirname, '..', 'renderer', 'html', 'login.html'))
        .then(() => {
            console.log('Main window loaded!')
        })
        .catch(err => console.error('Failed to load main window:', err));
});

const createAlertWindow = (title, width, height) => {
    alertWindow = new BrowserWindow({
        width: width,
        height: height,
        title: title,
        icon: path.join(__dirname, '..', 'renderer', 'assets', 'hard-disk.png'),
        resizable: false,
        webPreferences: {
            nodeIntegration: false,
            preload: path.join(__dirname, 'preload.js')
        }
    });

    //alertWindow.setMenu(null);

    alertWindow.loadFile(path.join(__dirname, '..', 'renderer', 'html', 'alert_modal.html')).then(() => {
        console.log('Alert window loaded!')
    })
        .catch(err => console.error('Failed to load alert window:', err));

    alertWindow.on('closed', () => {
        alertWindow = undefined;
    });
}

function showAlert(message) {
    if (alertWindow === undefined) {
        const title = 'Alert';
        const mainScreen = screen.getPrimaryDisplay();
        const { width, height } = mainScreen.size;
        createAlertWindow(title, width/4, height/4);
    }

    alertWindow.webContents.once('dom-ready', () => {
        alertWindow.webContents.executeJavaScript(`showAlert("${message}")`);
    });
}

app.whenReady().then(() => {
    const title = "Application";
    const mainScreen = screen.getPrimaryDisplay();
    const { width, height } = mainScreen.size;
    createMainWindow(title, width / 1.5, height / 1.5);

    app.on('activate', () => {
        if(BrowserWindow.getAllWindows().length === 0){
            createMainWindow(title, width, height);
        }
    });
});

app.on('window-all-closed', () => {
    if(!isMac){
        app.quit();
    }
});

ipcMain.handle('write-file', async (event, fileName, content) => {
    try {
        let filePath = path.join(__dirname, '..', '..', fileName);
        await fs.promises.writeFile(filePath, content);
        console.log(`File successfully written to ${filePath}`);
        return { success: true };
    } catch (error) {
        console.error('Failed to write file:', error);
        return { success: false, error: error.message };
    }
});

ipcMain.handle('delete-file', async (event, fileName) => {
    try {
        let filePath = path.join(__dirname, '..', '..', fileName);
        console.log(filePath);
        await fs.promises.unlink(filePath);
        console.log(`File ${filePath} successfully deleted`);
        return { success: true };
    } catch (error) {
        console.error('Failed to delete file:', error);
        return { success: false, error: error.message };
    }
});

ipcMain.handle('read-file', async (event, fileName) => {
    try {
        let filePath = path.join(__dirname, '..', '..', fileName);

        const content = await fs.promises.readFile(filePath, 'utf-8');
        return { success: true, content };
    } catch (error) {
        console.error('Error reading file:', error);
        return { success: false, error: error.message };
    }
});

ipcMain.handle('change-content', async (event, nextPage) => {
    try {
        html_page = nextPage;
        mainWindow.webContents.executeJavaScript(`
            document.body.classList.add('fade-out');
        `);

        await new Promise(resolve => setTimeout(resolve, 1000));
        await mainWindow.loadFile(path.join(__dirname, '..', 'renderer', 'html', nextPage));

        mainWindow.webContents.executeJavaScript(`
            document.body.classList.add('fade-in');
        `);
        return true;
    } catch (error) {
        console.error('Error changing content:', error);
        return false;
    }
});

ipcMain.handle('open-backup-dir-dialog', async (event) => {
    try {
        const result = await dialog.showOpenDialog({
            properties: ['openDirectory'],
        });

        if (result.canceled || result.filePaths.length === 0) {
            return {canceled: true}
        }

        const dirPath = result.filePaths[0];
        await fs.promises.writeFile(
            path.join(__dirname, '..', '..', 'dirBackup.json'),
            JSON.stringify({
                path: dirPath,
                structure: {}
            }, null, 2));

        return true;
    } catch (error) {
        console.error('Error opening file dialog:', error);
        return { error: error.message };
    }
});

ipcMain.handle('open-file-dialog', async (event) => {
    const result = await dialog.showOpenDialog({
        properties: ['openFile']
    });

    return result.filePaths[0] || '';
});

ipcMain.handle('check-file-exists', async (event, fileName) => {
    try {
        const filePath = path.join(__dirname, '..', '..', fileName);
        return await fs.promises.access(filePath)
            .then(() => true)
            .catch(() => false);
    } catch (error) {
        console.error('Error checking file existence:', error);
        throw error; // Propagate the error to the renderer process
    }
});

ipcMain.handle('show-alert', async (event, message) =>{
    showAlert(message);
});

ipcMain.on('close-alert-window', () => {
    if (alertWindow) {
        alertWindow.close();
        alertWindow = undefined;
    }
});
