using System;
using System.IO;
using System.Diagnostics;

namespace IMLibrary.NetProtocol
{
	/// <summary>
	/// Error handling.
	/// </summary>
	internal class Error
	{
		private static string m_Path = "";

		#region function DumpError

		/// <summary>
		/// Writes error to error log file.
		/// </summary>
		/// <param name="x"></param>
		/// <param name="stackTrace"></param>
		public static void DumpError(Exception x,StackTrace stackTrace)
		{
			try
			{
				string source = stackTrace.GetFrame(0).GetMethod().DeclaringType.FullName + "." + stackTrace.GetFrame(0).GetMethod().Name + "()";

				string errorText  = "";
					   errorText += "//------------- function:" + source + "  " + DateTime.Now.ToString() + "------------//\r\n";
					   errorText += x.Source + ":" + x.Message + "\r\n";
					   errorText += x.StackTrace;

				if(x is System.Data.SqlClient.SqlException){
					System.Data.SqlClient.SqlException sX = (System.Data.SqlClient.SqlException)x;
					errorText += "\r\n\r\nSql errors:\r\n";

					foreach(System.Data.SqlClient.SqlError sErr in sX.Errors){
						errorText += "\n";
						errorText += "Procedure: '" + sErr.Procedure + "'  line: " + sErr.LineNumber.ToString() + "  error: " + sErr.Number.ToString() + "\r\n";
						errorText += "Message: " + sErr.Message + "\r\n";
					}				
				}

				Error.WriteLog(m_Path + "ftpServiceError.log",errorText);
			}
			catch{
			}
		}

		#endregion

		#region function WriteLog(fileName,text)

		/// <summary>
		/// 
		/// </summary>
		/// <param name="fileName"></param>
		/// <param name="text"></param>
		public static void WriteLog(string fileName,string text)
		{
			try
			{
				// Try to parse directory path
				if(fileName.IndexOf("\\") > -1){
					string dirPath = fileName.Substring(0,fileName.LastIndexOf("\\"));
					// If there isn't such directory, create it.
                    if(!Directory.Exists(dirPath)){
						Directory.CreateDirectory(dirPath);
					}
				}

				using(FileStream fs = new FileStream(fileName,FileMode.OpenOrCreate, FileAccess.Write)){
					StreamWriter w = new StreamWriter(fs);      // create a Char writer 
					w.BaseStream.Seek(0, SeekOrigin.End);      // set the file pointer to the end
					w.Write(text + "\r\n");
					w.Flush();  // update underlying file
				}
			}
			catch{
			}
		}

		#endregion


		#region Propertis Implementation

		/// <summary>
		/// Gets or sets error file path.
		/// </summary>
		public static string ErrorFilePath
		{
			get{ return m_Path; }

			set{ m_Path = value; }
		}

		#endregion

	}
}
