using System;
using System.Web;
using System.Text.RegularExpressions;
using System.Configuration;
using System.Collections;
using System.Web.Security;
using System.Security.Principal;

using System.IO;


namespace flash
{
	/// <summary>
	/// MyHttpModule 的摘要说明。
	/// </summary>
	public class MyHttpModule : IHttpModule
	{
		public void Init(HttpApplication app)
		{
			app.AuthorizeRequest += new EventHandler(app_AuthorizeRequest);
		}

		public void Dispose() {}

		public static bool Rewrite(string url, ArrayList urls, System.Web.HttpApplication app)
		{
			URLRewrite urlRewrite = SiteUrls.GetSiteUrls().Match(url, urls);

			if (urlRewrite != null)
			{
				string query = Regex.Replace(url, urlRewrite.Pattern, urlRewrite.QueryString, RegexOptions.Compiled|RegexOptions.IgnoreCase);

				if (TryCache(urlRewrite, query, app))
				{
					return true;
				}
				app.Context.RewritePath(urlRewrite.Page, string.Empty, query);
				return true;
			}
			return false;
		}

		public static bool TryCache(URLRewrite url, string query, System.Web.HttpApplication app)
		{
			//缓存处理。
			if (app.Request.RequestType.ToLower() == "get" && app.Request.RawUrl.IndexOf("?")<0)
			{
				string key = url.Page + (query.Length>0? "?":"") + query;

				string CachePath = FileCache.CacheList[key.ToLower()] as string;
				if (CachePath != null && File.Exists(CachePath))
				{
					app.Context.RewritePath(CachePath);
					return true;
				}
			}
			return false;
		}

		private void app_AuthorizeRequest(object sender, EventArgs e)
		{
			HttpApplication app = (HttpApplication) sender;
			if (app.Request.Url.ToString().IndexOf("?")>0)
			{
				return;
			}

			Rewrite(app.Request.Path, SiteUrls.GetSiteUrls().Urls, app);

			if (System.Configuration.ConfigurationSettings.AppSettings["ip"] == "1")
			{
				using (StreamWriter sw = new StreamWriter(app.Server.MapPath("~/iplog.txt"), true))
				{
					sw.WriteLine("time:{3}\r\nip:{0}\r\nurl:{1}\r\nmeth:{2}\r\n----------\r\n", app.Request.UserHostAddress, app.Request.RawUrl, app.Request.RequestType, DateTime.Now.ToString("yyyyMMddhhmmss"));
					sw.Flush();
					sw.Close();
				}
			}
		}

		private void app_AuthenticateRequest(object sender, EventArgs e)
		{
			// 提取窗体身份验证 cookie
			string cookieName = FormsAuthentication.FormsCookieName;
			HttpCookie authCookie = HttpContext.Current.Request.Cookies[cookieName];

			if(null == authCookie)
			{
				// 没有身份验证 cookie。
				return;
			}

			FormsAuthenticationTicket authTicket = null;
			authTicket = FormsAuthentication.Decrypt(authCookie.Value);

			if (null == authTicket)
			{
				// 无法解密 Cookie。
				return; 
			}
			// 创建票证后，为 UserData 属性指定一个
			// 以管道符分隔的角色名字符串。
			string[] roles = authTicket.UserData.Split(new char[]{'|'});


			// 创建一个标识对象
			FormsIdentity id = new FormsIdentity( authTicket ); 

			// 该主体将通过整个请求。
			GenericPrincipal principal = new GenericPrincipal(id, roles);
			// 将新的主体对象附加到当前的 HttpContext 对象
			HttpContext.Current.User = principal;


		}
	}
}
