using System;
using System.Collections;
using System.Reflection;
using System.ComponentModel;
using System.Web;
using System.Web.SessionState;
using Orciid.Core;
using System.Diagnostics;
using System.Web.Mail;
using System.IO;
using Orciid.Core.Util;
using System.Text;

namespace Orciid 
{
	/// <summary>
	/// Global Application Settings and Methods
	/// </summary>
	/// <remarks>
	/// The application uses various application and session variables:
	/// <list type="table">
	/// <listheader>
	/// <term>Application variable</term>
	/// <description>Description</description>
	/// </listheader>
	/// <item><term>sysAdminEmailAddr</term><description></description></item>
	/// </list>
	/// <list type="table">
	/// <listheader>
	/// <term>Session variable</term>
	/// <description>Description</description>
	/// </listheader>
	/// <item><term>CurrentSlideshow</term><description></description></item>
	/// <item><term>CurrentUser</term><description></description></item>
	/// <item><term>LastBrowseSettings</term><description></description></item>
	/// <item><term>LastFolder</term><description></description></item>
	/// <item><term>LastSearch</term><description></description></item>
	/// <item><term>LastSearchResult</term><description></description></item>
	/// <item><term>SelectedImages</term><description></description></item>
	/// <item><term>FontSize</term><description>N=Normal, L=Large</description></item>
	/// <item><term>GuestAcceptedAgreements</term><description>ArrayList of collection ids</description></item>
	/// <item><term>TemporarySessionFiles</term><description>ArrayList of file names to be deleted at end of session</description></item>
	/// </list>
	/// </remarks>
	public class Global : System.Web.HttpApplication
	{
		public Global()
		{
			InitializeComponent();
		}	
		
		protected void Application_Start(Object sender, EventArgs e)
		{
			// Initialize core
			Initialization.Run(Assembly.GetAssembly(typeof(Orciid.Core.Collection)));
			// Initialize web application
			Initialization.Run(Assembly.GetExecutingAssembly());
			// Load configuration
			Configuration.Instance.Initialize(Context.Request.PhysicalApplicationPath);
		}
 
		protected void Session_Start(Object sender, EventArgs e)
		{
		}

		protected void Application_BeginRequest(Object sender, EventArgs e)
		{
			AnonymousUser.User.Activate(null);

			// see Microsoft Knowledge Base Article - 887459
			// http://support.microsoft.com/?kbid=887459
			if (Request.Path.IndexOf('\\') >= 0 ||
				System.IO.Path.GetFullPath(Request.PhysicalPath) != Request.PhysicalPath) 
			{
				throw new HttpException(404, "not found");
			}
		}

		protected void Application_EndRequest(Object sender, EventArgs e)
		{
		}

		protected void Application_AuthenticateRequest(Object sender, EventArgs e)
		{
		}

		protected void Application_Error(Object sender, EventArgs e)
		{
			Exception ex = Server.GetLastError();
			if (ex != null && ex.InnerException != null)
			{
				try
				{
					TransactionLog.Instance.AddException("Unhandled exception", 
						String.Format("{0} ({1})", Request.UserHostAddress, Request.UserHostName),
						ex);
				}
				catch
				{
				}
			}
		}

		protected void Session_End(Object sender, EventArgs e)
		{
			ArrayList tempfiles = Session["TemporarySessionFiles"] as ArrayList;
			if (tempfiles != null)
			{
				StringBuilder msg = new StringBuilder();
				foreach (string tempfile in tempfiles)
				{	
					if (!File.Exists(tempfile))
						continue;
					try
					{
						File.Delete(tempfile);
						msg.Append("Removed temporary file '")
							.Append(tempfile)
							.Append("'\n");
					}
					catch
					{
						msg.Append("Failed to remove temporary file '")
							.Append(tempfile)
							.Append("'\n");
					}
				}
				if (msg.Length > 0)
					TransactionLog.Instance.Add("Session Cleanup", msg.ToString());
			}
		}

		protected void Application_End(Object sender, EventArgs e)
		{

		}
			
		#region Web Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{    
		}
		#endregion
	}
}

