package com.interpress_project.modernshare.client.view;

import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Tray;
import org.eclipse.swt.widgets.TrayItem;

import com.interpress_project.modernshare.client.controller.actions.ExitAction;
import com.interpress_project.modernshare.client.controller.actions.ImageFactory;

public final class MfTaskTray {
	private final Shell shell;

	/**
	 * MfTaskTray
	 * @param vmgr
	 */
	public MfTaskTray(final ViewManager vmgr) {
		shell = vmgr.getShell();

		Tray tray = shell.getDisplay().getSystemTray();
		TrayItem trayItem = new TrayItem(tray, SWT.NONE);
		trayItem.setToolTipText("InterPress Hot Shot client agent");
		trayItem.setImage(ImageFactory.getInstance().getImage("sync"));

		trayItem.addListener(SWT.DefaultSelection, new Listener() {
			public void handleEvent(Event event) {
				// ダブルクリック(OPEN)
				NormalizeWindowHSCC();
			}
		});

		trayItem.addDisposeListener(new DisposeListener() {
			public void widgetDisposed(DisposeEvent disposeEvent) {
				TrayItem trayItem = (TrayItem) disposeEvent.getSource();
				trayItem.getImage().dispose();
			}
		});

		final Menu menu = new Menu(shell, SWT.POP_UP);

		MenuItem menuOpen = new MenuItem(menu, SWT.PUSH);
		menuOpen.setText("HotShotコンソールを開く(&O)");
		menuOpen.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				NormalizeWindowHSCC();
			}
		});

		MenuItem menuMinimum = new MenuItem(menu, SWT.PUSH);
		menuMinimum.setText("最小化(&C)");
		menuMinimum.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				MinimizeWindowHSCC();
			}
		});

		new MenuItem(menu, SWT.SEPARATOR);

		MenuItem menuExit = new MenuItem(menu, SWT.PUSH);

		/**
		 * タスクトレイアイコンからExitが選択されたときアプリを終了
		 */
		menuExit.setText("終了(&X)");
		menuExit.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(SelectionEvent e) {
				new ExitAction(vmgr).run();
			}
		});

		/**
		 * タスクトレイのアイコンが右クリックされたとき、メニューを表示するように設定
		 */
		trayItem.addListener(SWT.MenuDetect, new Listener() {
			public void handleEvent(Event event) {
				menu.setVisible(true);
			}
		});
	}

	/**
	 * NormalizeWindowHSCC
	 */
	private void NormalizeWindowHSCC() {
		shell.setMinimized(false);
		shell.setVisible(true);
	}

	/**
	 * MinimizeWindowHSCC
	 */
	private void MinimizeWindowHSCC() {
		shell.setMinimized(true);
		shell.setVisible(false);
	}
}
