// Main.cs
//
//  Copyright (C) 2008-2009 Christian Eide
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation; either version 2 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
//
using System;
using Gtk;
using System.Reflection;
using Mono.Unix;

namespace bareFTP
{
	class MainClass
	{
		
		
		public static void Main (string[] args)
		{
			ArgumentParser ap = new ArgumentParser();
			ap.Parse(args);
			
			Application.Init ();

			GLib.UnhandledExceptionHandler h = new GLib.UnhandledExceptionHandler (OnException);
			GLib.ExceptionManager.UnhandledException += h;
			
			Preferences.Config conf = new Preferences.Config(null);
			MainWindow win = new MainWindow (conf, ap.Debug);
			win.Show ();
			
			Application.Run ();
			
		}

		static void OnException (GLib.UnhandledExceptionArgs args)
  		{
   	 		bareFTP.Gui.Dialog.ExceptionDialog d = new bareFTP.Gui.Dialog.ExceptionDialog((Exception)args.ExceptionObject);
			ResponseType result = (ResponseType)d.Run ();
			
			args.ExitApplication = (result == ResponseType.Cancel);
			
  		}
		
		private static string version;
        public static string Version {
            get { 
                if (version != null) {
                    return version;
                }
                
                try {
                    AssemblyName name = Assembly.GetEntryAssembly ().GetName ();
                    version = String.Format ("{0}.{1}.{2}", name.Version.Major, 
                        name.Version.Minor, name.Version.Build);
					
					if(name.Version.Revision > 0)
						version += "-git";
                } catch {
                    version = "unknown";
                }
                
                return version;
            }
        }
		
	}
	
	public class ArgumentParser
	{
		private bool debug = false;
		
		public void Parse (string [] args)
		{
			for (int x = 0; x < args.Length; x++) 
			{
				bool quit = false;

				switch (args [x]) 
				{
					case "--version":
						PrintVersion();
						quit = true;
						break;
					case "--debug":
						debug = true;
						break;
					default:
						break;
				}

				if (quit == true)
					System.Environment.Exit (1);
					
			}
		}
		
		public bool Debug
		{
			get { return debug; }	
		}
		private void PrintVersion()
		{
			Console.Write ("bareftp " + MainClass.Version + Environment.NewLine + Environment.NewLine);
		}
			
	}
}