package org.positrium.chikarawo;

import java.awt.AWTException;
import java.awt.Dialog;
import java.awt.Frame;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.Label;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.Toolkit;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileNotFoundException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * append Genkidama controller to System Tray
 * 
 * @author token
 * 
 */
public class Gokuu {
	public static Log logger = LogFactory.getLog(Gokuu.class);

	private String version;

	private SystemTray tray;
	private TrayIcon normalTrayIcon;
	// private TrayIcon executeTrayIcon;

	private Image trayImage;

	public Gokuu(String version) {
		this.version = version;

		this.tray = SystemTray.getSystemTray();

		PopupMenu popup = new PopupMenu();
		File icon = new File("resource/genkidama.png");
		if (!icon.exists()) {
			logger.fatal("Fatal Error Occurs: " + icon.getAbsolutePath(),
					new FileNotFoundException());
			System.exit(1);
		}
		this.trayImage = Toolkit.getDefaultToolkit().getImage(icon.getPath());

		// settings
		MenuItem status = new MenuItem("settings");
		status.addActionListener(this.getStatusAction());
		popup.add(status);

		// separtor
		popup.addSeparator();

		// quit
		MenuItem quit = new MenuItem("quit");
		quit.addActionListener(this.getQuitAction());
		popup.add(quit);

		this.normalTrayIcon = new TrayIcon(trayImage, this.version, popup);
		this.normalTrayIcon.addMouseListener(this.getMouseLeftClickedAction());

		// PopupMenu executePop = new PopupMenu();
		// executePop.add(status);
		// executePop.add(sep);
		// executePop.add(quit);
		//
		// File icon2 = new File("resource/genkidama_inverse.png");
		// if (!icon2.exists()) {
		// logger.fatal("Fatal Error Occurs: " + icon2.getAbsolutePath(),
		// new FileNotFoundException());
		// System.exit(1);
		// }
		// this.executeTrayIcon = new TrayIcon(Toolkit.getDefaultToolkit()
		// .getImage(icon2.getPath()), this.version, executePop);

	}

	public void say(String message) {
		this.tray.getTrayIcons()[0].displayMessage(this.version, message,
				TrayIcon.MessageType.INFO);
	}

	public void shout() {
		if (SystemTray.isSupported()) {

			try {
				tray.add(normalTrayIcon);
			} catch (AWTException e1) {
				logger.error("Error Occurs:", e1);
			}

			this.say("mina ! orani chikarawo waketekure!");
		} else {
			logger.warn("System Tray not supported on your Environment");
		}
	}

	private ActionListener getStatusAction() {
		return new ActionListener() {
			private boolean frameOpend = false;

			public void actionPerformed(ActionEvent e) {
				if (!this.frameOpend) {
					this.frameOpend = true;
					final Dialog alert = new Dialog(new Frame(), version
							+ " settings");
					int row = 5, col = 1;
					alert.setLayout(new GridLayout(row, col));
					alert.setResizable(false);

					alert.add(new Label("port = "
							+ Integer.getInteger("listenPort").toString()));

					if ("".equals(System.getProperty("proxyHost"))) {
						alert
								.add(new Label(
										"direct mode (no secondary proxy)"));
					} else {
						alert.add(new Label("proxy host = "
								+ System.getProperty("proxyHost") + " : "
								+ Integer.getInteger("proxyPort")));
					}

					alert.add(new Label("title = "
							+ Boolean.getBoolean("title")));

					alert.add(new Label("Resume suspended download = "
							+ Boolean.getBoolean("resumeDownload")));

					alert.add(new Label("Touch Cache File = "
							+ Boolean.getBoolean(("touchCache"))));

					alert.setSize(300, 150);
					alert.addWindowListener(new WindowListener() {

						@Override
						public void windowActivated(WindowEvent arg0) {
						}

						@Override
						public void windowClosed(WindowEvent arg0) {
						}

						@Override
						public void windowClosing(WindowEvent arg0) {
							frameOpend = false;
							alert.dispose();
						}

						@Override
						public void windowDeactivated(WindowEvent arg0) {
						}

						@Override
						public void windowDeiconified(WindowEvent arg0) {
						}

						@Override
						public void windowIconified(WindowEvent arg0) {
						}

						@Override
						public void windowOpened(WindowEvent arg0) {
						}
					});
					alert.setVisible(true);

				}
			}
		};

	}

	private ActionListener getQuitAction() {
		return new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				say("yappa, yameta.");
				System.exit(0);
			}
		};
	}

	private MouseListener getMouseLeftClickedAction() {
		return new MouseListener() {
			private boolean frameOpend = false;

			@Override
			public void mouseClicked(MouseEvent arg0) {
				if (MouseEvent.BUTTON1 == arg0.getButton() && !frameOpend) {
					this.frameOpend = true;
					final Dialog alert = new Dialog(new Frame(), version
							+ " settings");
					int row = 5, col = 1;
					alert.setLayout(new GridLayout(row, col));
					alert.setResizable(false);

					alert.add(new Label("port = "
							+ Integer.getInteger("listenPort").toString()));

					if ("".equals(System.getProperty("proxyHost"))) {
						alert
								.add(new Label(
										"direct mode (no secondary proxy)"));
					} else {
						alert.add(new Label("proxy host = "
								+ System.getProperty("proxyHost") + " : "
								+ Integer.getInteger("proxyPort")));
					}

					alert.add(new Label("title = "
							+ Boolean.getBoolean("title")));

					alert.add(new Label("Resume suspended download = "
							+ Boolean.getBoolean("resumeDownload")));

					alert.add(new Label("Touch Cache File = "
							+ Boolean.getBoolean(("touchCache"))));

					alert.setSize(300, 150);
					alert.addWindowListener(new WindowListener() {

						@Override
						public void windowActivated(WindowEvent arg0) {
						}

						@Override
						public void windowClosed(WindowEvent arg0) {
						}

						@Override
						public void windowClosing(WindowEvent arg0) {
							frameOpend = false;
							alert.dispose();
						}

						@Override
						public void windowDeactivated(WindowEvent arg0) {
						}

						@Override
						public void windowDeiconified(WindowEvent arg0) {
						}

						@Override
						public void windowIconified(WindowEvent arg0) {
						}

						@Override
						public void windowOpened(WindowEvent arg0) {
						}
					});
					alert.setVisible(true);
				}

			}

			@Override
			public void mouseEntered(MouseEvent arg0) {
			}

			@Override
			public void mouseExited(MouseEvent arg0) {
			}

			@Override
			public void mousePressed(MouseEvent arg0) {
			}

			@Override
			public void mouseReleased(MouseEvent arg0) {
			}

		};
	}
	// public void switchTrayIcon() throws AWTException {
	// if (SystemTray.isSupported()) {
	// if (this.normalTrayIcon.equals(this.tray.getTrayIcons()[0])) {
	// this.say("Genkidamaaaa!!");
	// this.tray.remove(this.normalTrayIcon);
	// this.tray.add(this.executeTrayIcon);
	// } else {
	// this.say("chotto time..");
	// this.tray.remove(this.executeTrayIcon);
	// this.tray.add(this.normalTrayIcon);
	// }
	// }
	// }

}
