using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Specialized;
using System.Web;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Windows.Forms;

namespace Telerik.QuickStart.WinControls 
{
	class CodeViewer : WebControl, IPostBackEventHandler
	{
		#region Viewer Constants
		private const string tabDataDiv		= "<div style='display:none' id='{0}TabContent'>{1}</div>";
		private const string tabDivAJAX		= "<td align='center' valign='top' id='{0}Tab' onclick=\"displayTabAJAX('{0}','{1}'); return false\" onkeypress=\"displayTabAJAX('{0}','{1}'); return false\" class='tab'><img src=\"../Img/codeTabsArrowDisabled.gif\" style=\"border:none;\" alt=\"\" /><img src=\"../Img/codeTabs{0}.gif\" style=\"border:none;\" alt=\"\" /></td>";
		private const string scriptTag		= "<script type=\"text/javascript\">function displayTabPOSTBACK(tabName) {{ var postbackEvent = '{0}';eval(postbackEvent.replace('Description',tabName));}};var serviceUrl='{1}';displayTabAJAX('{2}','');</script>";
		private string[] allowedFileFormats	= {"Description", "js", "vb", "cs", "css", "xml", "config", "Images"};
		#endregion
	
		#region Public Properties
		private string _defaultTab = String.Empty;
		private string _applicationPath = String.Empty;
		private string _selectedExample = String.Empty;
		public string ApplicationPath
		{
			get
			{
				if (_applicationPath == String.Empty)
				{
					_applicationPath = HttpRuntime.AppDomainAppVirtualPath;
					if (!_applicationPath.EndsWith("/"))
					{
						_applicationPath += "/";
					}
				}
				return _applicationPath;
			}
		}
		public string DefaultTab
		{
			get
			{
				return _defaultTab;
			}
			set
			{
				_defaultTab = value;
			}
		}
		public string SelectedExample
		{
			get
			{
				return _selectedExample;
			}
			set
			{
				_selectedExample = value;
			}
		}
		#endregion

		protected HtmlGenericControl tabPlaceholder;
		protected HtmlGenericControl codePlaceholder;

		private CodeViewerCrawler exampleDir;

        private void PreRender_Handler(object sender,EventArgs e)
		{
			// CHANGED:
			tabPlaceholder = new HtmlGenericControl("div");
			codePlaceholder = new HtmlGenericControl("div");

			this.Controls.Add(tabPlaceholder);
			this.Controls.Add(codePlaceholder);

			//crawl the current path for all usable files
			if (exampleDir == null)
				exampleDir = new CodeViewerCrawler(MapPath(SelectedExample));
				//exampleDir = new Telerik.QuickStart.CodeViewerCrawler(Context.Server.MapPath(SelectedExample));
				// CHANGED:
				//exampleDir = new Telerik.QuickStart.CodeViewerCrawler(this.MapPathSecure(this.Page.TemplateSourceDirectory));
        	//add the files tabs(description,ascx,aspx,code..)
			RenderFileTabs();

			//add script to select the default tab on page load
			tabPlaceholder.Controls.Add(new LiteralControl(string.Format(scriptTag, this.Page.ClientScript.GetPostBackEventReference(this,"Description").Replace("'","\""), this.Page.ResolveUrl("~/common/codeviewer.asmx/GetCodeFile"), this.DefaultTab)));

			// add an empty div container where the new code viewer content will be added
			System.Web.UI.HtmlControls.HtmlGenericControl ajaxContainer = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
			ajaxContainer.Attributes.Add("id","codeViewerAjaxContainer");
			ajaxContainer.Attributes.Add("style","display:none");
			tabPlaceholder.Controls.Add(ajaxContainer);
			//add a div with the loading template
			System.Web.UI.HtmlControls.HtmlGenericControl loadingContainer = new System.Web.UI.HtmlControls.HtmlGenericControl("div");
			loadingContainer.Attributes.Add("id","codeViewerLoadingTemplate");
			loadingContainer.Attributes.Add("style","display:none");
			loadingContainer.InnerHtml="<img src=\"../Img/Loading.gif\" alt=\"loading\" style=\"margin-top: 100px;margin-left:300px;\"/>";
			tabPlaceholder.Controls.Add(loadingContainer);
		}

		private void RenderFileTabs()
		{
			string currentFile = string.Empty, fileContent = string.Empty;
			for (int i = 0; i < allowedFileFormats.Length; i++)
			{
				//get one file from each allowed format
				switch (allowedFileFormats[i])
				{
					case "Description":
						currentFile = exampleDir.GetOneFileOf("html");
						if (currentFile == string.Empty)
							currentFile = exampleDir.GetOneFileOf("htm");
						if (currentFile != string.Empty && (this.DefaultTab == String.Empty || this.DefaultTab == allowedFileFormats[i]))
							fileContent = CodeViewerHelper.RenderHtmlFile(currentFile);
						break;
					case "Images":
						// CHANGE:
						//currentFile = this.Page.TemplateSourceDirectory;
						//fileContent = Telerik.QuickStart.CodeViewerHelper.RenderImagesTabContent(this.Page.TemplateSourceDirectory, exampleDir.DefaultPageDirFiles, exampleDir.DefaultExampleImageFiles);
						//currentFile = Context.Server.MapPath(SelectedExample);
						currentFile = MapPath(SelectedExample);
						fileContent = CodeViewerHelper.RenderImagesTabContent(SelectedExample, exampleDir.DefaultPageDirFiles, exampleDir.DefaultExampleImageFiles);
						if (fileContent == string.Empty)
							currentFile = string.Empty;
						break;
					default:
						currentFile = exampleDir.GetOneFileOf(allowedFileFormats[i]);
						if (currentFile != string.Empty)
							fileContent = CodeViewerHelper.RenderFile(currentFile);
						break;
				}
				if (currentFile != string.Empty)
				{
					//select the first tab if no default
					if (this.DefaultTab == String.Empty)
						this.DefaultTab = allowedFileFormats[i];
					//initially display content only for the visible tab
					if (this.DefaultTab == allowedFileFormats[i])
						tabPlaceholder.Controls.Add(new LiteralControl(String.Format(tabDataDiv, allowedFileFormats[i], fileContent)));
					// CHANGE:
					//codePlaceholder.Controls.Add(new LiteralControl(String.Format(tabDivAJAX, allowedFileFormats[i], currentFile.Replace(Request.PhysicalApplicationPath,"~\\").Replace("\\","\\\\"), this.ApplicationPath)));
					codePlaceholder.Controls.Add(new LiteralControl(String.Format(tabDivAJAX, allowedFileFormats[i], currentFile.Replace("\\", "\\\\"))));
				}
				else
				{
					if (this.DefaultTab == allowedFileFormats[i])
						this.DefaultTab = string.Empty;
				}
			}
		}

		protected override void Render(HtmlTextWriter writer)
		{
			this.OnInit(new EventArgs());
			base.OnPreRender(new EventArgs());
			base.Render(writer);
		}

		#region Web Form Designer generated code
		override protected void OnInit(EventArgs e)
		{
			//
			// CODEGEN: This call is required by the ASP.NET Web Form Designer.
			//
			InitializeComponent();
			base.OnInit(e);
		}
		
		///		Required method for Designer support - do not modify
		///		the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.PreRender += new EventHandler (this.PreRender_Handler);
		}
		#endregion

		#region IPostBackEventHandler Members

		public void RaisePostBackEvent(string eventArgument)
		{
			if (eventArgument != null && eventArgument.Length>0)
				this.DefaultTab = eventArgument;
		}

		#endregion

		public static string MapPath(string fileName)
		{
			FileInfo fileInfo = new FileInfo(Application.ExecutablePath);
			DirectoryInfo directoryInfo = new DirectoryInfo(fileInfo.DirectoryName);
			return Path.Combine(directoryInfo.Parent.FullName, fileName);
		}
	}
}