using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Mail;
using System.Web;
using NLog;
using NLog.Targets;
using NLog.Targets.Wrappers;


namespace CharterDotCom.Common.Logging
{
	/// <summary>
	/// Logger
	/// </summary>
	public class Logger
	{
		private static NLog.Logger webLogger = NLog.LogManager.GetLogger("webLog");
		private static NLog.Logger serviceLogger = NLog.LogManager.GetLogger("serviceLog");
		private static NLog.Logger idTheftLogger = NLog.LogManager.GetLogger("idTheftLog");
		private static NLog.Logger idTheftEmailLogger = NLog.LogManager.GetLogger("idTheftEmailLog");
		private static NLog.Logger idQuartzEmailLogger = NLog.LogManager.GetLogger("quartzEmailLog");



		public static string GetLogFilePath(string targetName)
		{
			string fileName = null;

			if (LogManager.Configuration != null && LogManager.Configuration.ConfiguredNamedTargets.Count != 0)
			{
				Target target = LogManager.Configuration.FindTargetByName(targetName);
				if (target == null)
				{
					throw new Exception("Could not find target named: " + targetName);
				}

				FileTarget fileTarget = null;
				WrapperTargetBase wrapperTarget = target as WrapperTargetBase;

				// Unwrap the target if necessary.
				if (wrapperTarget == null)
				{
					fileTarget = target as FileTarget;
				}
				else
				{
					fileTarget = wrapperTarget.WrappedTarget as FileTarget;
				}

				if (fileTarget == null)
				{
					throw new Exception("Could not get a FileTarget from " + target.GetType());
				}

				var logEventInfo = new LogEventInfo { TimeStamp = DateTime.Now };
				fileName = fileTarget.FileName.Render(logEventInfo);
			}
			else
			{
				throw new Exception("LogManager contains no Configuration or there are no named targets");
			}


			var path = Path.GetDirectoryName(fileName);

			if (!Directory.Exists(path))
			{
				throw new Exception("Directory " + path + " does not exist");
			}

			return path;
		}




		/// <summary>
		/// Logs the specified message.
		/// </summary>
		/// <param name="message">The message.</param>
		public static void ServiceLog(string message)
		{
			var logMessage = string.Format("{0}\t{1}", "[Service]", message);

			try
			{
				serviceLogger.Log(NLog.LogLevel.Info, logMessage);
			}
			catch (Exception e)
			{
				System.Diagnostics.Debug.WriteLine("Log error: " + e.Message);
			}
		}

		/// <summary>
		/// Logs the specified message.
		/// </summary>
		/// <param name="message">The message.</param>
		public static void WebLog(string message)
		{
			var accountNumber = string.Empty;
			var firstName = string.Empty;

			var account = AccountManager.Instance().GetAccount();

			if (account != null)
			{
				accountNumber = account.OSSProvidedAccountNumber;
				var person = account.Person;
				if (person != null)
				{
					firstName = person.FirstName;
				}
			}

			var logMessage = string.Format("{0}\t{1}\t{2}", accountNumber, firstName, message);

			try
			{
				webLogger.Log(NLog.LogLevel.Info, logMessage);
			}
			catch (Exception e)
			{
				System.Diagnostics.Debug.WriteLine("Log error: " + e.Message);
			}
		}

		/// <summary>
		/// Logs the specified message.
		/// </summary>
		/// <param name="message">The message.</param>
		public static void IdTheftLog(string message)
		{
			var logMessage = string.Format("{0}:\t{1}", "[idtheft]", message);

			try
			{
				idTheftLogger.Log(NLog.LogLevel.Info, logMessage);
			}
			catch (Exception e)
			{
				System.Diagnostics.Debug.WriteLine("Log error: " + e.Message);
			}
		}

		/// <summary>
		/// Logs the specified message.
		/// </summary>
		/// <param name="FirstNameValue">The first name value.</param>
		/// <param name="LastNameValue">The last name value.</param>
		/// <param name="AddressValue">The address value.</param>
		/// <param name="CityValue">The city value.</param>
		/// <param name="StateValue">The state value.</param>
		/// <param name="ZipValue">The zip value.</param>
		/// <param name="PhoneNumberValue">The phone number value.</param>
		public static void IdTheftLog(string FirstNameValue, string LastNameValue, string AddressValue, 
			string CityValue, string StateValue, string ZipValue, string PhoneNumberValue)
		{
			var timeStamp = DateTime.Now;
			var ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

			var logMessage = string.Format("{0} - {1}\t{2}\t{3}\t{4}\t{5}\t{6}\t{7}\t{8}",
				timeStamp.ToShortDateString(), timeStamp.ToShortTimeString(), ipAddress, FirstNameValue, LastNameValue, AddressValue, CityValue, StateValue, ZipValue, PhoneNumberValue);

			var emailMessage = string.Format("Date: {0}\nTime: {1}\nIP Address: {2}\n\nFirst Name: {3}\nLast Name:  {4}\nAddress:    {5}\nCity:       {6}\nState:      {7}\nZip:        {8}\nPhone:      {9}",
				timeStamp.ToShortDateString(), timeStamp.ToShortTimeString(), ipAddress, FirstNameValue, LastNameValue, AddressValue, CityValue, StateValue, ZipValue, PhoneNumberValue);

			try
			{
				idTheftLogger.Log(NLog.LogLevel.Info, logMessage);
				idTheftEmailLogger.Log(NLog.LogLevel.Info, emailMessage);
			}
			catch (Exception e)
			{
				System.Diagnostics.Debug.WriteLine("Log error: " + e.Message);
			}
		}

/*
		/// <summary>
		/// Sends the email.
		/// </summary>
		/// <param name="fromMailAddress">From mail address.</param>
		/// <param name="toMailAddresses">To mail addresses.</param>
		/// <param name="subject">The subject.</param>
		/// <param name="body">The body.</param>
		/// <param name="isHtml">if set to <c>true</c> [is HTML].</param>
		private static void SendEMail(string fromMailAddress, string toMailAddresses, string subject, string body, bool isHtml = false)
		{
			var smtpServer = System.Configuration.ConfigurationManager.AppSettings.Get("SMTPSERVER");

			// DLCorpIDTheft@charter.com
			var server = "";
			var username = "";
			var password = "";

			var client = new SmtpClient(server, 465);
			client.EnableSsl = true;
			client.Credentials = new NetworkCredential(username, password);

			var toMailAddress = toMailAddresses.Split(';');

			foreach (var to in toMailAddress)
			{
				var mailMsg = new MailMessage(fromMailAddress, to) { Subject = subject, Body = body, IsBodyHtml = isHtml };
				// client.SendAsync(mailMsg, null);
				client.Send(mailMsg);
			}
		}
*/

		public static void QuartzLog(string message)
		{
			var logMessage = string.Format("{0}\t{1}", "[quartz]", message);

			try
			{
				idQuartzEmailLogger.Log(NLog.LogLevel.Info, logMessage);
			}
			catch (Exception e)
			{
				System.Diagnostics.Debug.WriteLine("Log error: " + e.Message);
			}
		}
	}
}
