using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Net.Mail;
using System.Web;
using CharterDotCom.WebSite.Library;
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},{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},{1},{2}", accountNumber, firstName, message);

			try
			{
				LogEventInfo logEvent = new LogEventInfo(NLog.LogLevel.Info, "", message);
				logEvent.Properties["accountname"] = firstName;
				logEvent.Properties["accountnumber"] = accountNumber;
				webLogger.Log(logEvent);

				// ... and in your NLog.config file: 
				// ${event-context:item=OrderId} -- renders OrderId

				// 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}:,{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},{2},{3},{4},{5},{6},{7},{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);
				LogEventInfo logEvent = new LogEventInfo(NLog.LogLevel.Info, "", "");
			
				logEvent.Properties["ipaddress"] = ipAddress;
				logEvent.Properties["firstname"] = FirstNameValue;
				logEvent.Properties["lastname"] = LastNameValue;
				logEvent.Properties["address"] = AddressValue;
				logEvent.Properties["city"] = CityValue;
				logEvent.Properties["state"] = StateValue;
				logEvent.Properties["zip"] = ZipValue;
				logEvent.Properties["phonenumber"] = PhoneNumberValue;
				idTheftLogger.Log(logEvent);

				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},{1}", "[quartz]", message);

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