// mcs -pkg:gtk-sharp TrayLib.cs TrayTest.cs -out:TrayTest.exe
using Gtk;
using Glade;
using System;
using System.IO;
using System.Diagnostics;
using System.Threading;

using Novell.CASA;
using Novell.CASA.MiCasa.Common;
using Novell.CASA.MiCasa.Communication;

 
public class TrayCasa
{

	[Glade.Widget] 
	Gtk.Label			label86,
						label88;

	[Glade.Widget] 
	Gtk.Entry	 		entryMasterPassword1, 
						entryMasterPassword2, 
						entryMasterPassword3, 
						entryMasterPassword4;

	[Glade.Widget] 
	Gtk.Dialog 			dialogLogin;

#if W32
	private static System.Windows.Forms.NotifyIcon		notifyIcon;
	public static System.Drawing.Icon					m_iconNormal;
	public static System.Drawing.Icon					m_iconLocked;
#endif


	Gtk.Window mainWindow = new Window("Test");
	private static bool firstInstance;
	

	public static void Main()
	{

		// check for already running				
		//Mutex mutex = new Mutex(false, "Local\\"+"CASATray", out firstInstance); 
		
		//if (firstInstance)
		{
			// initialises the application
			Application.Init();
			// creates the tray icon
			TrayCasa casaTray = new TrayCasa();
			// runs application
			Application.Run();	

		//	mutex.ReleaseMutex();
		}
	}
 
	public TrayCasa()
	{

#if W32		
		Stream		s = null;
		notifyIcon = new System.Windows.Forms.NotifyIcon();
		try 
		{
			s = File.OpenRead("../images/notify1.ico");
			m_iconNormal = new System.Drawing.Icon(s);
			notifyIcon.Icon = m_iconNormal;
		}

		catch (Exception e)
		{
			//MessageBox.Show("File 'notify.ico' cannot be found", "Error");
			Console.WriteLine(e.ToString());
			Console.WriteLine("File 'notify.ico' cannot be found");
			return;
		}

		finally 
		{
			if (s != null) 
			{
				s.Close();					
			}
		}

		try 
		{
			s = File.OpenRead("../images/notifyLocked.ico");
			m_iconLocked = new System.Drawing.Icon(s);
			
		}

		catch (Exception e)
		{			
			Console.WriteLine("File 'notifyLocked.ico' cannot be found");
			return;
		}

		finally 
		{
			if (s != null) 
			{
				s.Close();					
			}
		}
		//notifyIcon.Click +=new EventHandler(notifyIcon_Click);
		notifyIcon.DoubleClick +=new EventHandler(notifyIcon_DoubleClick);
		notifyIcon.MouseUp +=new System.Windows.Forms.MouseEventHandler(notifyIcon_MouseUp);
		notifyIcon.Text = "CASA Manager";
		notifyIcon.Visible = true;	
#endif	
#if LINUX
		/* in order to receive signals, we need a eventbox,	because Gtk.Image doesn't receive signals */
		EventBox eb = new EventBox();
		eb.Add(new Image(Stock.MissingImage, IconSize.Menu)); // using stock icon
		// hooking event
		eb.ButtonPressEvent += new ButtonPressEventHandler (this.OnImageClick);
		Egg.TrayIcon icon = new Egg.TrayIcon("Test");
		icon.Add(eb);
		// showing the trayicon
		icon.ShowAll();
#endif
	}
	
	private void ShowContextMenu()
	{
		Menu popupMenu = new Menu(); // creates the menu 
 
		MenuItem miSep = new MenuItem();
		MenuItem miSep2 = new MenuItem();
		MenuItem miSep3 = new MenuItem();

		ImageMenuItem menuLaunchGUI = new ImageMenuItem ("Launch CASAManager");
		Image appimg = new Image(Stock.New, IconSize.Menu);
		menuLaunchGUI.Image = appimg; // sets the menu item's image
		menuLaunchGUI.Activated +=new EventHandler(menuLaunchGUI_Activated);		
		popupMenu.Add(menuLaunchGUI);
		popupMenu.Add(miSep);

		ImageMenuItem menuLockMiCasa = new ImageMenuItem ("Lock Secrets");	
	
		//appimg = new Image(Stock.Close, IconSize.Menu);
		appimg = new Image("gtk-dialog-authentication", IconSize.Menu);
		menuLockMiCasa.Image = appimg; // sets the menu item's image		
		menuLockMiCasa.Activated +=new EventHandler(menuLockMiCasa_Activated);		

		ImageMenuItem menuUnLockMiCasa = new ImageMenuItem ("Unlock Secrets...");		
		appimg = new Image(Stock.Open, IconSize.Menu);
		menuUnLockMiCasa.Image = appimg; // sets the menu item's image
		menuUnLockMiCasa.Activated +=new EventHandler(menuLockMiCasa_Activated);

		if (MiCASAStore.IsLocked())
		{
			menuLockMiCasa.Sensitive = false;			
		}
		else
		{
			menuUnLockMiCasa.Sensitive = false;
		}

		popupMenu.Add(menuLockMiCasa);
		popupMenu.Add(menuUnLockMiCasa);
	
		popupMenu.Add(miSep2);

		ImageMenuItem menuDestroyMiCasa = new ImageMenuItem ("Destroy Secrets");
		appimg = new Image(Stock.Delete, IconSize.Menu);
		menuDestroyMiCasa.Image = appimg; // sets the menu item's image
		menuDestroyMiCasa.Activated +=new EventHandler(menuDestroyMiCasa_Activated);
		popupMenu.Add(menuDestroyMiCasa);

		ImageMenuItem menuOptionsMiCasa = new ImageMenuItem ("Options ....");
		menuOptionsMiCasa.Sensitive = false;
		popupMenu.Add(menuOptionsMiCasa);
		
		popupMenu.Add(miSep3);

		// creates a menu item with no image as default
		ImageMenuItem menuPopup1 = new ImageMenuItem ("Exit");				
		appimg = new Image(Stock.Quit, IconSize.Menu);
		menuPopup1.Image = appimg; // sets the menu item's image
		popupMenu.Add(menuPopup1); // adds the menu item to the menu
		
		// hooks a event when the user clicks the icon
		menuPopup1.Activated += new EventHandler(this.OnPopupClick);
		popupMenu.ShowAll(); // shows everything
		
		// pops up the actual menu when the user right clicks
		//popupMenu.Popup(null, null, null, IntPtr.Zero, args.Event.Button, args.Event.Time);
		
		popupMenu.Popup();
	}

	private void OnImageClick (object o, ButtonPressEventArgs args) // handler for mouse click
	{
		if (args.Event.Button == 3) //right click
		{
			ShowContextMenu();
		}
	}
	private void OnPopupClick(object o, EventArgs args)
	{
		Application.Quit(); // quits the application when the users clicks the popup menu
	}
#if W32
	private void notifyIcon_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
	{		
		if (e.Button == System.Windows.Forms.MouseButtons.Right)
			ShowContextMenu();
	}
#endif

	private void menuLaunchGUI_Activated(object sender, EventArgs e)
	{
		// launch the GUI
		Process myProcess = new Process();
#if W32
		ProcessStartInfo myProcessStartInfo = new ProcessStartInfo("CASAManager.exe");
#else
		ProcessStartInfo myProcessStartInfo = new ProcessStartInfo("mono");
		myProcessStartInfo.Arguments = "/opt/novell/CASA/bin/CASAManager.exe";
#endif								
		myProcessStartInfo.UseShellExecute = false;
		myProcessStartInfo.RedirectStandardOutput = true;
		myProcess.StartInfo = myProcessStartInfo;
		myProcess.Start();
	}

	private void menuLockMiCasa_Activated(object sender, EventArgs e)
	{

		if (MiCASAStore.IsLocked())
		{
			//if( false == miCASA.IsSecretPersistent(1,"") )
			{    		    
				//Logger.DbgLog("GUI:CasaMain.Login() - IsMasterPasswordSet returned false");    		    
#if W32
				Glade.XML gxmlTemp = new Glade.XML ("../images/casa-1.5.glade", "dialogLogin", null);
#endif
#if LINUX
				Glade.XML gxmlTemp = new Glade.XML ("/opt/novell/CASA/images/casa-1.5.glade", "dialogLogin", null);
#endif
				gxmlTemp.Autoconnect (this);
				//dialogLogin.TransientFor = windowMain;        
				
				label86.Text = "Enter your Master Password to unlock your secrets";
				entryMasterPassword3.Text="";
				label88.Hide();
				entryMasterPassword4.Hide();
				dialogLogin.Show();
			}						
		}
		else
		{
			MiCasaRequestReply.Send(MiCasaRequestReply.VERB_LOCK_STORE);			
#if W32	
			notifyIcon.Icon = m_iconLocked;
#endif
		}
	}

	private void menuDestroyMiCasa_Activated(object sender, EventArgs e)
	{
		// prompt user 						
		MessageDialog md=new MessageDialog(mainWindow,Gtk.DialogFlags.Modal,
				Gtk.MessageType.Warning,
				Gtk.ButtonsType.OkCancel,
				"This will destroy all of your secrets.\r\nAre you sure?");

			md.SetPosition(Gtk.WindowPosition.Center);
			md.Response +=new ResponseHandler(md_Response);
			md.Modal = true;
			md.Show();						
	}

	private void md_Response2(object o, ResponseArgs args)
	{
		MessageDialog md = (MessageDialog)o;
		if (md != null)
		{
			md.Destroy();			
		}
	}

	private void md_Response(object o, ResponseArgs args)
	{
		if (args.ResponseId.Equals(Gtk.ResponseType.Ok))
		{
			MiCasaRequestReply.Send(MiCasaRequestReply.VERB_REMOVE_ALL_SECRETS);
		}

		MessageDialog md = (MessageDialog)o;
		if (md != null)
		{
			md.Destroy();			
		}
	}

	// test code
	public void okbuttonLogin_clicked(object abj, EventArgs args)
	{    
		if( 0 == miCASA.SetMasterPassword(0, entryMasterPassword3.Text) )
		{
			// unlock it
			MiCasaRequestReply.Send(MiCasaRequestReply.VERB_UNLOCK_STORE, entryMasterPassword3.Text);
#if W32
			notifyIcon.Icon = m_iconNormal;
#endif
			dialogLogin.Destroy();  
		
		}
		else
		{
			// prompt user 						
			MessageDialog md=new MessageDialog(mainWindow,Gtk.DialogFlags.Modal,
				Gtk.MessageType.Warning,
				Gtk.ButtonsType.Ok,
				"Master Password entered is incorrect");

			md.Response +=new ResponseHandler(md_Response2);
			md.SetPosition(Gtk.WindowPosition.Center);		
			md.Modal = true;
			md.Show();
		}				
	}
    
    
    
	public void closebuttonLogin_clicked(object abj, EventArgs args)
	{
		dialogLogin.Destroy();  
	}
    
    
	public void OnDialogLoginDeleted(object obj, DeleteEventArgs args) 
	{		    			
		args.RetVal = true;        		
	}
    
	public void on_entryMasterPassword3_activate(object obj, EventArgs args)
	{
		if( true == entryMasterPassword4.Visible )
			entryMasterPassword4.HasFocus = true;
		else if( "" != entryMasterPassword3.Text )
			okbuttonLogin_clicked(obj, args);
	}
    
	public void on_entryMasterPassword4_activate(object obj, EventArgs args)
	{
		okbuttonLogin_clicked(obj, args);
	}

    /*
	public bool IsMasterPasswordSet()
	{		    	
		string MICASA_PASSCODE_BY_MASTER_PASSWD_FILE = "/.miCASAPCByMPasswd";
		string fileName = Environment.GetEnvironmentVariable("HOME")+MICASA_PASSCODE_BY_MASTER_PASSWD_FILE;           		
		return (File.Exists(fileName));
	}
	*/

	private void notifyIcon_DoubleClick(object sender, EventArgs e)
	{
		menuLockMiCasa_Activated(sender, e);
	}
}