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

namespace VoServices.Footprint.Web
{
	/// <summary>
	/// Summary description for Includer.
	/// </summary>
	public class Includer : System.Web.UI.WebControls.WebControl
	{
		public string HrefBase;
		public string PathBase;
		public string Src;

		public Includer()
		{
			Src = "";
		}

		protected override void Render(System.Web.UI.HtmlTextWriter writer)
		{
			if (Src == "") return;
		
//			try
//			{
				// Determining filename to load	
				string buffer = LoadFile(Page.Server.MapPath(PathBase + Src));
					
				// Retrieving content between body tags
				Regex bodyregex = new Regex("<body[^>]*>(.*)</body", RegexOptions.IgnoreCase | RegexOptions.Singleline);
				Match m = bodyregex.Match(buffer);
				buffer = m.Groups[1].Value;
		
				string _relativePath = Page.Request.FilePath.Substring(0, Page.Request.FilePath.LastIndexOf("/") + 1);
				_relativePath += PathBase;		
				_relativePath += Src.Substring(0, Src.LastIndexOf("/") + 1);
			
		
				string output = "";
				string src;
				int    index = 0;
				if (_relativePath != "/")
				{
					Regex srcregex = new Regex("<[^>]+\\s(src|background|href)\\s*=(\"[^\"]*\"|[^\\s]*)", RegexOptions.IgnoreCase);
					m = srcregex.Match(buffer);
					while (m.Success)
					{
						output += buffer.Substring(index, m.Groups[2].Index - index);
							
						src = m.Groups[2].Value.Trim('"');
                        if (src.StartsWith("/") || (src.IndexOf(":") > 0))
						{
							output += "\"" + src + "\"";
						}
						else if (m.Groups[1].Value.ToLower() == "href")
						{
							string tmp = Src.Substring(0, Src.LastIndexOf("/") + 1) + src;
							
							output +=  "\"" + HrefBase + ReducePath(tmp) + "\"";
						}
						else
						{
							output += "\"" + _relativePath + src + "\"";
						}
							
						output += buffer.Substring(m.Groups[2].Index + m.Groups[2].Length, m.Index + m.Length - m.Groups[2].Index - m.Groups[2].Length);
		
						index = m.Groups[2].Index + m.Groups[2].Length;
		
						m = m.NextMatch();
					}
				}
				output += buffer.Substring(index);
		
				output = output.Trim();
				writer.Write(output);
//			}
//			catch (System.Exception)
//			{
//				//writer.Write(e.ToString());
//			}
		}
		
		private string LoadFile(string fileName)
		{
			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();
		
			return Encoding.Default.GetString(buffer);
		}


		private string ReducePath(string path)
		{
			string[] parts = path.Split('/');
			int count = parts.Length;
			int i = 0;
			while (i < count)
			{
				if (parts[i] == ".." && i > 0)
				{
					count -= 2;
					for (int j = i - 1; j < parts.Length - 2; j++)
						parts[j] = parts[j + 2];
					i--;
				}
				else
					i++;
			}

			string res = "";
			for (int j = 0; j < count; j++)
			{
				if (j != 0) res += "/";
				res += parts[j];
			}

			return res;
		}
	}
}
