using System;
using System.Xml;
using System.Collections;
using System.Configuration;
using System.Collections.Specialized;
using System.Web.Caching;
using System.Web;
using System.Text;
using System.Text.RegularExpressions;

namespace flash
{
	/// <summary>
	/// SiteUrls 的摘要说明。
	/// </summary>
	public class SiteUrls
	{
		#region 内部属性和方法
		string SiteUrlsFile = HttpContext.Current.Server.MapPath("~/SiteUrls.config");
		private ArrayList _Urls;
		public ArrayList Urls
		{
			get
			{
				return _Urls;
			}
			set
			{
				_Urls = value;
			}
		}

		private NameValueCollection _Paths;
		public NameValueCollection Paths
		{
			get
			{
				return _Paths;
			}
			set
			{
				_Paths = value;
			}
		}
		
		private SiteUrls()
		{
			string applicationPath = HttpContext.Current.Request.ApplicationPath;

			if (applicationPath == "/")
			{
				applicationPath = string.Empty;
			}

			Urls = new ArrayList();

			Paths = new NameValueCollection();
			Paths.Add("home", applicationPath);

			XmlDocument xml = new XmlDocument();

			xml.Load(SiteUrlsFile);

			XmlNode root = xml.SelectSingleNode("SiteUrls");
			foreach(XmlNode n in root.ChildNodes)
			{
				if (n.NodeType != XmlNodeType.Comment && n.Name.ToLower() == "rewrite")
				{
					XmlAttribute name = n.Attributes["name"];
					XmlAttribute path = n.Attributes["path"];
					XmlAttribute page = n.Attributes["page"];
					XmlAttribute querystring = n.Attributes["querystring"];
					XmlAttribute pattern = n.Attributes["pattern"];

					if (name != null && path != null && page != null && querystring != null && pattern != null)
					{
						Paths.Add(name.Value, applicationPath + path.Value);
						Urls.Add(new URLRewrite(name.Value, Paths["home"]+pattern.Value, Paths["home"]+page.Value, querystring.Value));
					}
				}
			}
		}
		#endregion

		public static SiteUrls GetSiteUrls()
		{
			string CacheKey = "SiteUrls";
			SiteUrls urls = System.Web.HttpContext.Current.Cache["SiteUrls"] as SiteUrls;
			if (urls == null)
			{
				urls = new SiteUrls();
				System.Web.HttpContext.Current.Cache.Insert(CacheKey, urls, new CacheDependency(urls.SiteUrlsFile), DateTime.MaxValue, TimeSpan.Zero, CacheItemPriority.High, null);
			}

			return urls;
		}

		public URLRewrite Match(string url, ArrayList urls)
		{
			foreach(URLRewrite urlRewrite in urls)
			{
				if (Regex.IsMatch(url, urlRewrite.Pattern, RegexOptions.Compiled|RegexOptions.IgnoreCase))
				{
					return urlRewrite;
				}
			}
			return null;
		}

		public string Show(int id)
		{
			return string.Format(Paths["Show"], id);
		}
	}
}
