using System;
using System.Web;
using System.Web.UI;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;

namespace flash
{
	/// <summary>
	/// PageBase 的摘要说明。
	/// </summary>
	public class PageBase : Page
	{
		private string _CacheFile;

		/// <summary>
		/// 缓存文件路径
		/// </summary>
		public string CacheFile
		{
			get
			{
				return _CacheFile;
			}
			set
			{
				_CacheFile = value;
			}
		}
		//// <summary>
		///  重写默认的HtmlTextWriter方法，修改form标记中的value属性，使其值为重写的URL而不是真实URL。
		/// </summary>
		/// <param name="writer"></param>
		protected override void Render(HtmlTextWriter writer)
		{

			if (writer is System.Web.UI.Html32TextWriter)
			{
				writer = new FormFixerHtml32TextWriter(writer.InnerWriter);
			}
			else
			{
				writer = new FormFixerHtmlTextWriter(writer.InnerWriter);
			}

			if (WriteCache(writer))
			{
			}
			else
                base.Render(writer);
		}

		public virtual bool WriteCache(HtmlTextWriter writer)
		{
			if (CacheFile!=null && CacheFile!=string.Empty && Request.RequestType.ToLower() == "get" && Request.RawUrl.IndexOf("?")<0 )
			{
				string key = Request.Url.PathAndQuery.ToString();
				if (!FileCache.CacheList.ContainsValue(CacheFile))
				{
					string filename = HttpContext.Current.Server.MapPath(CacheFile);
                    string path = filename.Substring(0, filename.LastIndexOf('\\'));
                    if (!Directory.Exists(path))
                        Directory.CreateDirectory(path);
					lock (this)
					{
						StreamWriter sw = new StreamWriter(filename, false, Encoding.Default);

						base.Render(new FetchHtmlWriter(writer, sw));
						sw.Flush();
						sw.Close();
						FileCache.CacheList[key.ToLower()] = CacheFile;

						return true;
					}
				}
			}
			return false;
		}
	}

	public class FormFixerHtml32TextWriter : System.Web.UI.Html32TextWriter
	{
		private string _url; // 假的URL

		public FormFixerHtml32TextWriter(TextWriter writer):base(writer)
		{
			_url = HttpContext.Current.Request.RawUrl;
		}

		public override void WriteAttribute(string name, string value, bool encode)
		{
			// 如果当前输出的属性为form标记的action属性，则将其值替换为重写后的虚假URL
			if (_url != null && string.Compare(name, "action", true) == 0)
			{
				value = _url;
			}
			base.WriteAttribute(name, value, encode);
		}
	}

	    
	public class FormFixerHtmlTextWriter : System.Web.UI.HtmlTextWriter
	{
		private string _url;
		public FormFixerHtmlTextWriter(TextWriter writer):base(writer)
		{
			_url = HttpContext.Current.Request.RawUrl;
		}

		public override void WriteAttribute(string name, string value, bool encode)
		{
			if (_url != null && string.Compare(name, "action", true) == 0)
			{
				value = _url;
			}

			base.WriteAttribute(name, value, encode);
		}
	}
}
