import { TrayIcon } from '@tauri-apps/api/tray';
import { getCurrentWindow } from '@tauri-apps/api/window';
import { currentSettings } from './settings';
import { get } from 'svelte/store';
import { Menu } from '@tauri-apps/api/menu';

const mainWindow = getCurrentWindow();

export async function setupTrayIcon() {
	// Prevent the window from closing when the close button is clicked
	mainWindow.onCloseRequested((event) => {
		const settings = get(currentSettings);
		if (settings.closeToTray) {
			event.preventDefault();
			mainWindow.hide();
		}
	});
	const menu = await Menu.new({
		items: [
			{
				id: 'toggle',
				text: 'Show/Hide',
				action: async () => {
					const visible = await mainWindow.isVisible();
					console.log(visible);
					if (visible) {
						mainWindow.hide();
					} else {
						mainWindow.show();
					}
				}
			},
			{
				id: 'quit',
				text: 'Quit',
				action: () => {
					mainWindow.destroy();
				}
			}
		]
	});

	const options = {
		menu,
		menuOnLeftClick: true
	};

	return await TrayIcon.new(options);
}
