using System;
using System.Text;

namespace Novell.CASA.MiCasa.Common
{
	/// <summary>
	/// Summary description for MessageObject.
	/// </summary>
	/// 
	[Serializable]
	public class WrappedObject
	{
		public static string DEFAULT_KEYCHAIN_ID = "SSCS_SESSION_KEY_CHAIN_ID\0";

		private int m_verb = 0;
		private string m_KeychainID = null;
		private string m_SecretID = null;
		private string m_KeyID = null;		

		private object m_object;

		private int m_rcode = 0;
		private string m_errorMsg;

		public WrappedObject(int rcode, string errorMsg)
		{
			m_rcode = rcode;
			m_errorMsg = errorMsg;
		}

		public WrappedObject(int verb, string sKeychainID, string sSecretID, string sKeyID, object theObject)
		{
			m_verb = verb;
			if (sKeychainID != null)
				m_KeychainID = sKeychainID + '\0';
			else
				m_KeychainID = DEFAULT_KEYCHAIN_ID;

			if (sSecretID != null)
			{
				if (sSecretID.StartsWith("SS_CredSet"))
					m_SecretID = "SS_CredSet:" + EscapeReservedChars(sSecretID.Substring(12)) + '\0';
				else
					m_SecretID = "SS_CredSet:" + EscapeReservedChars(sSecretID) + '\0';
			}
	
			if (sKeyID != null)
				m_KeyID = EscapeReservedChars(sKeyID); // + '\0';

			// serialize the object
			m_object = theObject;						
		}

		public string GetKeyID()
		{
			return m_KeyID;
		}

		public string GetSecretID()
		{
			return m_SecretID;
		}

		public string GetKeychainID()
		{
			return m_KeychainID;
		}

		public object GetObject()
		{
			return m_object;
		}

		public void SetObject(object theobject)
		{
			m_object = theobject;
		}

		public int GetAction()
		{
			return m_verb;
		}

		public void SetError(int rcode, string message)
		{
			m_rcode = rcode;
			m_errorMsg = message;						
		}

		public int GetReturnCode()
		{
			return m_rcode;
		}

		public string GetReturnMessage()
		{
			return m_errorMsg;
		}

		private string EscapeReservedChars(string origString)
		{
			StringBuilder sb = new StringBuilder();
			for (int i=0; i<origString.Length; i++)
			{
				switch (origString[i])
				{
					case ':'  :	
					{
						sb.Append("\\");
						break;
					}
					case '\\' :		
					{
						sb.Append("\\");
						break;
					}
					case '='  :
					{
						sb.Append("\\");
						break;
					}					
					
				}
				sb.Append(origString[i]);				
			}
			return sb.ToString();
		}
	}
}