/***********************************************************************
 * 
 *  Copyright (C) 2005-2006 Novell, Inc. All Rights Reserved.
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License as published by the Free Software Foundation; version 2.1
 *  of the License.
 *
 *  This library 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
 *  Library Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, Novell, Inc.
 * 
 *  To contact Novell about this file by physical or electronic mail, 
 *  you may find current contact information at www.novell.com.
 * 
 ***********************************************************************/

namespace Novell.CASA.GUI {


using System;
using System.Text;
using System.Diagnostics;
using System.IO;    
using System.Threading;
using Gtk;
using Glade;


public class Common
{

	public const int 		STORE_MICASA    		= 0,
					STORE_FIREFOX   		= 1,
					STORE_MOZILLA 	  		= 2,
					STORE_KDEWALLET			= 3,
					STORE_GNOMEKEYRING 		= 4;
					
	public static bool 		IS_MICASA_AVAILABLE		= true,
					IS_FIREFOX_AVAILABLE		= false,
					IS_MOZILLA_AVAILABLE		= false,
					IS_KDEWALLET_AVAILABLE		= false,
					IS_GNOMEKEYRING_AVAILABLE	= false;
											
	public static bool 		IS_MICASA			= true,
					IS_FIREFOX			= false,
					IS_MOZILLA			= false,
					IS_KDEWALLET			= false,
					IS_GNOMEKEYRING			= false;
							
	public static bool 		IS_LINUX			= false,
					IS_WINDOWS			= false;
							
  	public static string 	GladeFile			= null,
  					DebugLogFile			= null;
 
 
  	///##############################################################
  	/// SPI CONSTANTS
  	///
  	
  	public static int 	 	MAX_STORES 				= 10;
  	
  	public static string 	STORENAME_MICASA		= "miCASA",
						 	STORENAME_FIREFOX		= "Firefox",
						 	STORENAME_MOZILLA		= "Mozilla",
						 	STORENAME_KDEWALLET		= "KDE KWallet",
						 	STORENAME_GNOMEKEYRING	= "GNOME Keyring";
	
	
	///##############################################################
  	/// SDI CONSTANTS
  	///
  	
	//Operations 
	public static int 		OPERATION_ADD_SECRET	 = 0,
					  		OPERATION_ADD_KEY		 = 1,
					  		OPERATION_MODIFY_KEY	 = 2,
					  		OPERATION_DELETE_SECRET	 = 3,
							OPERATION_DELETE_KEY	 = 4;

  	//Limits
	public static int		MAX_ARRAY_ELEMENTS		 = 10;
	public static int 	 	MAX_NATIVE_ELEMENTS 	 = 8;
		
	public static string 	NATIVEINFO_FOLDERNAME 	 = "Folder Name";
	public static string 	NATIVEINFO_TYPEID 	 	 = "Type of Secret";
	public static string 	NATIVEINFO_SYNC 		 = "Syncronization Status";
	public static string 	NATIVEINFO_SYNCTYPE 	 = "Syncronization Type";
	public static string 	NATIVEINFO_MODIFIEDTIME  = "Last Modified Time";
		
	public static int       INDEX_NATIVEINFO_FOLDERNAME 	= 0,
						    INDEX_NATIVEINFO_TYPEID 	 	= 1,
		    				INDEX_NATIVEINFO_SYNC 		 	= 2,
							INDEX_NATIVEINFO_SYNCTYPE 	 	= 3,
							INDEX_NATIVEINFO_MODIFIEDTIME 	= 4,
							INDEX_NATIVEINFO_ACCESSEDTIME 	= 5,
							INDEX_NATIVEINFO_CREATEDTIME 	= 6,
							INDEX_NATIVEINFO_WALLETLASTACCESSEDTIME 	= 7;


	public static string	LINUX_HELP_PATH		= "file:///usr/share/doc/packages/CASA/help/";
	public static string	WINDOWS_HELP_PATH	= "..\\help\\";
    	
	///##############################################################
	/// ARG CONSTANTS
	public static string	ARG_SHOW_TRAY_ICON			= "-tray";
	public static string	ARG_DEBUG					= "-debug";

	///#############################################################
	///CasaIcons path
#if W32
	public static string	CASAICONS = "../images/CASAicons.ico";
#endif
#if LINUX
	public static string	CASAICONS = "/usr/share/doc/packages/CASA/images/CASAicons.ico";
#endif
	
  	///##############################################################
  	/// ERROR CODES
  	
   	public static int 		STATUS_SUCCESS                 		= 0,
   							STATUS_FAILURE				  		= 1,
    						
    						// POLICY STATUS CODE RANGE: 2 - 20
    						STATUS_POLICY_COULDNOTBESAVED		= 2,
    						STATUS_POLICY_POLICYNOTFOUND		= 3,
    						
    						// STORE STATUS CODE RANGE: 21 - 40  
     						STATUS_STORE_INVALIDSTOREID			= 21,
     						STATUS_STORE_DATANOTFOUNDINSTORE	= 22,
     						STATUS_STORE_UNSUPPORTEDOPERATION	= 23,
     						STATUS_STORE_ADINITFAILED			= 24,
     						STATUS_STORE_AGGREGATEFAILED		= 25,
     						STATUS_STORE_READFAILED				= 26,
     						STATUS_STORE_UPDATEFAILED			= 27;
 
 
 	///##############################################################
  	/// STATIC ROUTINES
 
     public static void ShowErrorDialog(Exception exp)
     {
     	Console.WriteLine("CASA-EXCEPTION: " + exp.ToString());         
     }
     
     
     
     public static void ShowErrorDialog(int errorCode)
     {
     	Console.WriteLine("CASA-ERROR: " + errorCode);         
     }  
     
     ///#######################################################################
    /// READ PLATFORM
    
    /// <summary>
	/// Routine to read the operating system of the target machine.
	/// IS_LINUX, IS_WINDOWS flags are set.
	/// Path to Glade file is set in this routine.
	/// </summary>
    public static void ReadPlatform()
    {
    	Logger.DbgLog("GUI:CasaMain.SetGladeFilePath() - BEGIN");
    	
    	int platform = (int)Environment.OSVersion.Platform;
		
	if ( (128 == platform) || (4 == platform) )
        {
        	IS_LINUX = true;        	
        	GladeFile = "/usr/share/doc/packages/CASA/images/casa.glade";        	
        	
        	if( !File.Exists(GladeFile) )
			{
				Logger.DbgLog("GUI:CasaMain.SetGladeFilePath() - ERROR: Glade file could not be found.");
				//Gtk.Application.Quit();
				Environment.Exit(-1);
        	}
			
        	Logger.DbgLog("GUI:CasaMain.SetGladeFilePath() - IS_LINUX = " + IS_LINUX);        	
        }
        else
        {
        	IS_WINDOWS = true;        	        	
        	GladeFile = "..\\images\\casa.glade";        	
        	if( !File.Exists(GladeFile) )
		{
			Logger.DbgLog("GUI:CasaMain.SetGladeFilePath() - ERROR: Glade file could not be found.");
			Environment.Exit(-1);
        	}
        	Logger.DbgLog("GUI:CasaMain.SetGladeFilePath() - IS_WINDOWS = " + IS_WINDOWS);              			     
        }
                
        Logger.DbgLog("GUI:CasaMain.SetGladeFilePath() - END");
    }
    
    
    ///#######################################################################
    /// SINGLE INSTANCE CHECK
    
    /// <summary>
    /// MainWindow delete window handler
    /// </summary>

	public static bool CheckForSingleInstance()
	{
		bool bRet=false;;
		
		if( true == IS_LINUX )
		{			
        	Process mgrProcess = null;
        	StreamReader sReader = null;
		
			try
        	{
            	mgrProcess = new Process();
            	ProcessStartInfo mgrProcessStartInfo = new ProcessStartInfo("ps" );
            	mgrProcessStartInfo.Arguments = "Tuxh";
            	mgrProcessStartInfo.UseShellExecute = false;
            	mgrProcessStartInfo.RedirectStandardOutput = true;
            	mgrProcess.StartInfo = mgrProcessStartInfo;
            	mgrProcess.Start();
            	mgrProcess.WaitForExit();
            	sReader = mgrProcess.StandardOutput;
            	string str = sReader.ReadLine();
            	int num = 0;
            	while( str != null)
            	{
                	str = sReader.ReadLine();
                	if(str != null)
                	{
                    	if(str.EndsWith("CASAManager.exe"))
                    	{
                        	num++;
                    	}
                	}
           		}
           		if( num > 1 )
               		bRet = true;
           		else
               		bRet = false;
        	}
        	catch(Exception e)
        	{
            	Logger.DbgLog("GUI:CasaMain.CheckIfAnotherInstanceIsRunning() " + e.ToString());
            	bRet = false;
        	}
			
			if(mgrProcess != null)
            	mgrProcess.Close(); 
        	if(sReader != null)
            	sReader.Close();
        	//return bRet;
			
		}
		else if( true == IS_WINDOWS )
		{
			bRet = false;
			//return(false);
		}	
		return bRet;	
	}
 
	public static bool IsTrayAvailable()
	{
		if (true == IS_LINUX)
			return true;
		else if (true == IS_WINDOWS)
			return true;
		else
			return false;
	}     

	public static bool IsArgSet(string[] args, string argToCheck)
	{
		if (args != null)
		{
			for (int i=0; i<args.Length; i++)
			{
				if (argToCheck.Equals(args[i].ToLower()))
					return true;
			}
		}
		
		return false;
	}

	private static string GetLocale()
	{
		if (IS_LINUX)
			return "en/";
		else
			return "en\\";
	}

	private static string GetHelpPath()
	{
		if (IS_LINUX)
			return LINUX_HELP_PATH;
		else
			return WINDOWS_HELP_PATH;
	}

	public static bool ShowHelpUrl(string sHelpFilename)
	{
		// get absolute path and locale
		string sUrl = GetHelpPath() + GetLocale() + sHelpFilename;
		return ShowUrl(sUrl);
	}


	public static bool ShowUrl(string url)
	{
		
		Process urlShowProcess = new Process();
			
		if (Common.IS_LINUX)
		{
			String sCurrentDesktop = Environment.GetEnvironmentVariable("WINDOWMANAGER");
			if (sCurrentDesktop != null && (sCurrentDesktop.IndexOf("kde") > 0))
				urlShowProcess.StartInfo.FileName = "kde-open";
			else
				urlShowProcess.StartInfo.FileName = "gnome-open";

			urlShowProcess.StartInfo.Arguments = url;
		}
		else
			urlShowProcess.StartInfo.FileName = url;		
			
		try
		{
			urlShowProcess.Start();
			urlShowProcess.WaitForExit();
		}
		catch (Exception e)
		{
			Logger.DbgLog(e.Message);						
			Logger.DbgLog(e.StackTrace);
			return false;
		}

		if (urlShowProcess.ExitCode == 0)
			return true;
		else
			return false;
	}
}

}
///##################################################################
///							END OF FILE
///##################################################################