package org.positrium.ui.chikarawo;

import java.awt.AWTException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.io.File;
import java.io.FileNotFoundException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.positrium.ui.FileResource;
import org.positrium.ui.GenkidamaSettingsDto;
import org.positrium.ui.MenuFactory;
import org.positrium.ui.TrayControl;
import org.seasar.framework.container.SingletonS2Container;
import org.seasar.framework.container.factory.SingletonS2ContainerFactory;

/**
 * append Genkidama controller to System Tray
 * 
 * @author token , 2009 CC BY-SA
 * @version $Rev: 210 $
 * 
 */
public class Chikarawo implements TrayControl {
	public static Log logger = LogFactory.getLog(Chikarawo.class);

	public SystemTray tray;
	private GenkidamaSettingsDto app;

	private MyTrayIcon normalTrayIcon;

	// private Image trayImage;

	public Chikarawo() {
		this.app = SingletonS2Container.getComponent("genkidamaSettings");
		this.tray = java.awt.SystemTray.getSystemTray();

		MenuFactory menufactory = SingletonS2Container.getComponent("menuFactory");
		PopupMenu popup = (PopupMenu) menufactory.createPopupMenu();

		try {
			this.normalTrayIcon = new MyTrayIcon(app.version, popup);
		} catch (FileNotFoundException e) {
			this.fatalStop(
					"Fatal:",
					e.getMessage());
		}

		LogWindow.getInstance().show();
	}

	@Override
	public void fatalStop(String title, String message) {
		new ErrorDialog(title, message);

	}

	/**
	 * トレイアイコンにtooltipを出力する
	 * 
	 * @param message
	 */
	public void showTooltip(String message) {
		this.tray.getTrayIcons()[0].displayMessage(
				app.version,
				message,
				TrayIcon.MessageType.INFO);
	}

	@Override
	public void openTray() {
		if (SystemTray.isSupported()) {
			try {
				tray.add(normalTrayIcon);
			} catch (AWTException e1) {
				logger.error(
						"Error Occurs:",
						e1);
			}
		} else {
			logger.warn("System Tray not supported on your Environment");
		}
	}

	// TODO for ActionSourceClasses
	//	
	// private final Vector<StateChangeListener> listenerList = new
	// Vector<StateChangeListener>();
	// public void addGenkidamaStateChangeListener(
	// GenkidamaStateChangeListener listener) {
	// if (!listenerList.contains(listener))
	// listenerList.add(listener);
	// }
	//
	// public void stateChange(int cmd) {
	// Vector list = (Vector) listenerList.clone();
	// Enumeration e = list.elements();
	// GenkidamaStateChangeEvent evt = new GenkidamaStateChangeEvent(this, cmd);
	// while (e.hasMoreElements()) {
	// GenkidamaStateChangeListener listener = (GenkidamaStateChangeListener) e
	// .nextElement();
	// listener.serverStateChanged(evt);
	// }
}
