using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

using net.catcert.psis;

namespace net.catcert.psis.utils
{
	public sealed class Utils
	{
		public static void Pause() 
		{
			Pause(null);
		}

		public static void Pause(string message) 
		{
			if ( message != null ) 
			{
				message = message.Trim();
				if ( message.Length > 0 ) Console.WriteLine(message);
			}
			Console.Write("Press any key when ready");
			Console.ReadLine();
		}

		public static void ShowRequest(VerifyRequest request)
		{
			Console.WriteLine("Request:");
			Console.WriteLine("--------");
			Console.WriteLine( MessageToString(request) );
			Console.WriteLine();
		}

		public static void ShowResponse(VerifyResponse response)
		{
			Console.WriteLine("Response:");
			Console.WriteLine("---------");
			Console.WriteLine( MessageToString(response) );
			Console.WriteLine();
		}

		public static byte[] Base64File(string file) 
		{
			StreamReader reader = new StreamReader(file);
			string tmp="";
			string contents="";

			while (tmp != null)
			{
				tmp = reader.ReadLine();
				if (tmp!=null) 
				{
					contents = contents + tmp;
				}
			}
			reader.Close();

			return Base64Decode(contents);
		}

		public static XmlElement XMLFile(string file) 
		{
			FileStream stream = new FileStream(file, FileMode.Open);
			XmlDocument doc = new XmlDocument();
			doc.PreserveWhitespace=true;
			doc.Load(stream);

			return doc.DocumentElement;
		}

		public static byte[] Base64Decode(string data)
		{
			try
			{
				UTF8Encoding encoder = new UTF8Encoding();  
				Decoder utf8Decode = encoder.GetDecoder();

				byte[] todecode_byte = Convert.FromBase64String(data);
				return todecode_byte;
			}
			catch(Exception e)
			{
				throw new Exception("Error in base64Decode" + e.Message);
			}
		}

		public static byte[] StringToBytes(string data)
		{
			return Encoding.UTF8.GetBytes(data);
		}

		public static string MessageToString(object Object) 
		{
			XmlSerializer serializer = null;
			MemoryStream writer = new MemoryStream();

			serializer= new XmlSerializer( Object.GetType() );
			
			serializer.Serialize(writer, Object);

			return (Encoding.UTF8.GetString(writer.GetBuffer(), 0, writer.GetBuffer().Length));
		}
	}
}
