using System;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Threading;
using System.Globalization;
using System.Configuration;
using ASPNET.StarterKit.TimeTracker.BusinessLogicLayer;

namespace ASPNET.StarterKit.TimeTracker.Web
{
	// Global Application
	public class Global : System.Web.HttpApplication
	{
		// Configuation constants used for retrieving application setting values from the
		// web.config file.
		public const string CfgKeyConnString = "ConnectionString";
		public const string CfgKeyUserAcctSource = "UserAccountSource";
		public const string CfgKeyDefaultRole = "DefaultRoleForNewUser";
		public const string CfgKeyFirstDayOfWeek = "FirstDayOfWeek";

		// Constants used to reference data stored in cookies
		public const string UserRoles = "userroles";
		public const string MobileUserRoles = "mobileuserroles";

		public Global()
		{
		}	
		
		//*********************************************************************
		//
		// Application_BeginRequest Event
		//
		// The Application_BeginRequest method is an ASP.NET event that executes 
		// on each web request into the portal application.  
		//
		// The thread culture is set for each request using the language
		// settings specified in the browser.
		// 
		//*********************************************************************

		protected void Application_BeginRequest(Object sender, EventArgs e)
		{
			try
			{
				if (Request.UserLanguages != null)
					Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(Request.UserLanguages[0]);
				else
					// Default to English if there are no user languages
					Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us");

				Thread.CurrentThread.CurrentUICulture = Thread.CurrentThread.CurrentCulture;
			}
			catch (Exception ex)
			{
				Thread.CurrentThread.CurrentCulture = new CultureInfo("en-us");
			}
		}
                          
		//*********************************************************************
		//
		// Application_AuthenticateRequest Event
		//
		// If the client is authenticated with the application, then determine
		// which security roles he/she belongs to and replace the "User" intrinsic
		// with a custom IPrincipal security object that permits "User.IsInRole"
		// role checks within the application
		//
		// Roles are cached in the browser in an in-memory encrypted cookie.  If the
		// cookie doesn't exist yet for this session, create it.
		//
		//*********************************************************************

		protected void Application_AuthenticateRequest(Object sender, EventArgs e)
		{
			string userInformation = String.Empty;

			if (Request.IsAuthenticated == true) 
			{
				// Create the roles cookie if it doesn't exist yet for this session.
				if ((Request.Cookies[UserRoles] == null) || (Request.Cookies[UserRoles].Value == "")) 
				{
					// Retrieve the user's role and ID information and add it to
					// the cookie
					TTUser user = new TTUser(User.Identity.Name);
					if (!user.Load())
					{
						// The user was not found in the Time Tracker database so add them using
						// the default role.  Specifying a UserID of 0 will result in the user being 
						// inserted into the database.
						TTUser newUser = new TTUser(0, Context.User.Identity.Name,
							String.Empty, ConfigurationSettings.AppSettings[CfgKeyDefaultRole]);
						newUser.Save();
						user = newUser;
					}
                
					// Create a string to persist the role and user id
					userInformation = user.UserID + ";" + user.Role + ";" + user.Name;

					// Create a cookie authentication ticket.
					FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(
						1,                              // version
						User.Identity.Name,			    // user name
						DateTime.Now,                   // issue time
						DateTime.Now.AddHours(1),       // expires every hour
						false,                          // don't persist cookie
						userInformation                    
						);

					// Encrypt the ticket
					String cookieStr = FormsAuthentication.Encrypt(ticket);

					// Send the cookie to the client
					Response.Cookies[UserRoles].Value = cookieStr;
					Response.Cookies[UserRoles].Path = "/";
					Response.Cookies[UserRoles].Expires = DateTime.Now.AddMinutes(1);

					// Add our own custom principal to the request containing the user's identity, the user id, and
					// the user's role 
					Context.User = new CustomPrincipal(User.Identity, user.UserID, user.Role, user.Name);
				}
				else 
				{
					// Get roles from roles cookie
					FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies[UserRoles].Value);
					userInformation = ticket.UserData;

					// Add our own custom principal to the request containing the user's identity, the user id, and
					// the user's role from the auth ticket
					string [] info = userInformation.Split( new char[] {';'} );
					Context.User = new CustomPrincipal(
						User.Identity, 
						Convert.ToInt32(info[0].ToString()), 
						info[1].ToString(),
						info[2].ToString());
				}
			}
		}

		//*********************************************************************
		//
		// GetApplicationPath Method
		//
		// This method returns the correct relative path when installing
		// the portal on a root web site instead of virtual directory
		//
		//*********************************************************************

		public static string GetApplicationPath(HttpRequest request) 
		{
			string path = string.Empty;
			try 
			{
				if(request.ApplicationPath != "/")
					path = request.ApplicationPath;
			}
			catch (Exception e)
			{
				throw e;
			}
			return path;
		}
	}
}