const { shell } = require('electron')
const isMac = process.platform === 'darwin'

let mainWindow, port;
let user = false;
let isAdmin = false;
let isAdvanced = false;

function setWindowMenu(window, newPort) {
    mainWindow = window;
	port = newPort;
	updateUserMenu();
}

function setUserMenu(newUser) {
	user = newUser;
	isAdmin = newUser.role === 'admin';
	isAdvanced = newUser.role === 'advanced';
	updateUserMenu();
}

function resetUserMenu() {
	user = false;
	isAdmin = false;
	isAdvanced = false;
	updateUserMenu();
}

function updateUserMenu() {
    const signInMenuItem = {
        label: 'Sign In',
        click: async () => {
            mainWindow.loadURL(`http://localhost:${port}/signin`);
        }
    };

    const logoutMenuItem = {
        label: 'Logout ' + user.username,
        click: async () => {
            mainWindow.loadURL(`http://localhost:${port}/logout`);
        }
    };

    const dashboardMenuItem = {
        label: 'Dashboard',
        click: async () => {
            mainWindow.loadURL(`http://localhost:${port}/dashboard`);
        }
    };

    const settingsMenuItem = {
        label: 'Settings',
        click: async () => {
            mainWindow.loadURL(`http://localhost:${port}/settings`);
        }
    };

    const booksMenuItem = {
        label: 'Books',
        click: async () => {
            mainWindow.loadURL(`http://localhost:${port}/books`);
        }
    };

    const usersMenuItem = {
        label: 'Users',
        click: async () => {
            mainWindow.loadURL(`http://localhost:${port}/users`);
        }
    };

    // Update the menu template based on user status
    let userMenuItem = user ? logoutMenuItem : signInMenuItem;
    let additionalItems = [];
	let separator =	{ type: 'separator' };

    // Add admin-specific items
    if (isAdmin) {
        additionalItems.push(separator, booksMenuItem, usersMenuItem, dashboardMenuItem, settingsMenuItem);
    } else if (isAdvanced) {
		additionalItems.push(separator, booksMenuItem, settingsMenuItem);
	} else if (user) {
		additionalItems.push(booksMenuItem);
	}

    // Build the final submenu
    const submenu = [
        {
            label: 'Home',
            click: async () => {
                mainWindow.loadURL(`http://localhost:${port}/`);
            }
        },
        ...additionalItems,
		{ type: 'separator' },
        userMenuItem,
        isMac ? { role: 'close' } : { role: 'quit' }
    ];

    // Update the File menu item
    template[1].submenu = submenu;

    // Set the menu
    mainWindow.setMenu(null);
    const { Menu } = require('electron');
    const menu = Menu.buildFromTemplate(template);
    Menu.setApplicationMenu(menu);
}

let template = [
	// { role: 'appMenu' }
	...(isMac
		? [{
			label: 'LiteLib',
			submenu: [
				{ role: 'about', label: 'About LiteLib'},
				{ type: 'separator' },
				{ role: 'services' },
				{ type: 'separator' },
				{ role: 'hide', label: 'Hide LiteLib'},
				{ role: 'hideOthers' },
				{ role: 'unhide' },
				{ type: 'separator' },
				{ role: 'quit' }
			]
		}]
		: []),
	// { role: 'fileMenu' }
	{
		label: 'File',
		submenu: [
			{
				label: 'Home',
				click: async () => {
					mainWindow.loadURL(`http://localhost:${port}/`);
				}
			},
			user ? {
				label: 'Sign In',
				click: async () => {
					mainWindow.loadURL(`http://localhost:${port}/signin`);
				}
			} : {
				label: 'Logout',
				click: async () => {
					mainWindow.loadURL(`http://localhost:${port}/logout`);
				}
			},
			{ type: 'separator' },
			isMac ? { role: 'close' } : { role: 'quit' }
		]
	},
	// { role: 'editMenu' }
	{
		label: 'Edit',
		submenu: [
			{ role: 'undo' },
			{ role: 'redo' },
			{ type: 'separator' },
			{ role: 'cut' },
			{ role: 'copy' },
			{ role: 'paste' },
			...(isMac
				? [
					{ role: 'pasteAndMatchStyle' },
					{ role: 'delete' },
					{ role: 'selectAll' },
					{ type: 'separator' },
					{
						label: 'Speech',
						submenu: [
							{ role: 'startSpeaking' },
							{ role: 'stopSpeaking' }
						]
					}
				]
				: [
					{ role: 'delete' },
					{ type: 'separator' },
					{ role: 'selectAll' }
				])
		]
	},
	// { role: 'viewMenu' }
	{
		label: 'View',
		submenu: [
			{ role: 'reload' },
			{ role: 'forceReload' },
			{ role: 'toggleDevTools' },
			{ type: 'separator' },
			{ role: 'resetZoom' },
			{ role: 'zoomIn' },
			{ role: 'zoomOut' },
			{ type: 'separator' },
			{ role: 'togglefullscreen' }
		]
	},
	// { role: 'windowMenu' }
	{
		label: 'Window',
		submenu: [
			{ role: 'minimize' },
			{ role: 'zoom' },
			...(isMac
				? [
					{ type: 'separator' },
					{ role: 'front' },
					{ type: 'separator' },
					{ role: 'window' }
				]
				: [
					{ role: 'close' }
				])
		]
	},
	{
		role: 'help',
		submenu: [
			{
				label: 'GitHub',
				click: async () => {
					await shell.openExternal('https://github.com/cs340-24/litelib')
				}
			}
		]
	}
]

module.exports = { template, setWindowMenu, setUserMenu, resetUserMenu};
