using System;
using System.Data;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Data.OleDb;
using System.ComponentModel;
using System.Collections.Specialized;
using System.Configuration;

namespace VoServices.Footprint.Web
{
	/// <summary>
	///		Summary description for Layout.
	/// </summary>
	public class BasePageTemplated : BasePage
	{

		public string LayoutTemplate;

		protected string _layoutHtml;

		public BasePageTemplated():base()
		{
			LayoutTemplate = "";
		}

		override protected void OnInit(EventArgs e)
		{
			base.OnInit(e);
			if (LayoutTemplate == "") LayoutTemplate = ConfigurationSettings.AppSettings["LayoutTemplate"];

			
		}

		override protected void Render(System.Web.UI.HtmlTextWriter writer)
		{
			LoadTemplate();

			if (_relativePath != "")
			{
				Regex srcregex = new Regex("<[^>]+\\s(src|background|href)\\s*=(\"[^\"]*\"|[^\\s]*)", RegexOptions.IgnoreCase);

				_layoutHtml = srcregex.Replace(_layoutHtml, new MatchEvaluator(this.SrcReplacer));
			}

			// Replacing wildcards
			_layoutHtml = _layoutHtml.Replace("#section#", Section);

			// Replacing image src -s:
			_layoutHtml = _layoutHtml.Replace("\"images", "\"" + _relativePath + "/images");
			//_layoutHtml = _layoutHtml.Replace("\"/images", "\"" + _relativePath + "/images");

			// Parsing special tags in the template
			Regex layoutregex = new Regex("<layout:([a-zA-Z]+)([^>]*)>", RegexOptions.IgnoreCase);
			Match m = layoutregex.Match(_layoutHtml);
			int i = 0;
			Control control;

			while (m.Success)
			{
				writer.Write(_layoutHtml.Substring(i, m.Index - i));
				//writer.WriteLine("\r\n<!-- ---------- {0} ---------- -->", m.Groups[1].Value);

				switch (m.Groups[1].Value.ToLower())
				{
					case "banner":
					{
						Banner banner = new Banner();
						banner.InitializeAsUserControl(this);

						Regex parregex = new Regex("\\s([a-zA-Z]+)=(\"[^\"]*\"|[^\\s]*)", RegexOptions.IgnoreCase);
						Match m2 = parregex.Match(m.Groups[2].Value);

						while (m2.Success)
						{
							switch (m2.Groups[1].Value.ToLower())
							{
								case "width":
								{
									banner.Width = Int32.Parse(m2.Groups[2].Value.Trim('"'));
									break;
								}
								case "height":
								{
									banner.Height = Int32.Parse(m2.Groups[2].Value.Trim('"'));
									break;
								}
								case "type":
								{
									banner.Type = m2.Groups[2].Value.Trim('"');
									break;
								}
							}
							m2 = m2.NextMatch();
						}
						
						banner.Position = this.Section;
						banner.RenderControl(writer);
						break;
					}
					case "header":
					{
						writer.WriteLine("<title>" + Title + "</title>");
						//writer.WriteLine("<meta name=\"Keywords\" content=\"" + Keywords + "\">");
						//writer.WriteLine("<link rel=\"stylesheet\" type=\"text/css\" href=\"" + _relativePath + "/des01/" + (string) Session["Css"] + "\">");
						break;
					}
					case "middle":
					{
						foreach (Control em in Controls)
						{
							if (em.GetType() == typeof(System.Web.UI.HtmlControls.HtmlForm))
							{
								em.RenderControl(writer);
							}
						}
						break;
					}
					default:
					{
						if ((control = this.FindControl("Layout" + m.Groups[1].Value)) != null)
						{
							control.RenderControl(writer);
						}
						break;
					}
				}

				//writer.WriteLine("\r\n<!-- ---------- {0} end ---------- -->", m.Groups[1].Value);

				i = m.Index + m.Length;
				m = m.NextMatch();
			}

			writer.Write(_layoutHtml.Substring(i));
		}

		private string SrcReplacer(Match match)
		{
			string buffer = match.Value;
			string src = match.Groups[2].Value.Trim('"');
			
			if (src.StartsWith("/"))
			{
				src = "\"" + Request.ApplicationPath + src + "\"";
				buffer = buffer.Replace(match.Groups[2].Value, src);
			}

			return buffer;
		}

		private void LoadTemplate()
		{
			string filename = Server.MapPath(_relativePath + "/" + LayoutTemplate);
			FileStream infile = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);

			byte[] buffer = new byte[infile.Length];

			infile.Read(buffer, 0, buffer.Length);
			infile.Close();

			_layoutHtml = Encoding.Default.GetString(buffer);
		}
	}
}
