using System;
using System.Web;
using System.Text.RegularExpressions;

namespace DebriefingSoftware.Common
{
	public static class HttpContextExtensions
	{
		public static string GetWebRoot(this HttpContext httpContext)
		{
			if (httpContext == null)
				throw new InvalidOperationException("Code is running under not a web application.");

			return httpContext.Request.Url.GetLeftPart(UriPartial.Authority)
					 + httpContext.Request.ApplicationPath;
		}

		public static string GetShortWebRoot(this HttpContext httpContext)
		{
			if (httpContext == null)
				throw new InvalidOperationException("Code is running under not a web application.");

			return httpContext.Request.ApplicationPath;
		}

		public static string GetPathWithoutShortWebRoot(this HttpContext httpContext, string fullPath)
		{
			if (httpContext == null)
				throw new InvalidOperationException("Code is running under not a web application.");

			var result = fullPath;

			result = result.Replace(httpContext.Request.ApplicationPath, "");
			result = Regex.Replace(result, @"^/?(.*?)/?$", "$1");

			return result;
		}

		public static string GetWebFolderBeforePage(this HttpContext httpContext)
		{
			if (httpContext == null)
				throw new InvalidOperationException("Code is running under not a web application.");

			return httpContext.Request.Url.Segments.Length > 1 ? Regex.Replace(httpContext.Request.Url.Segments[httpContext.Request.Url.Segments.Length - 2], @"^/?(.*?)/?$", "$1") : String.Empty;
		}

		public static string GetWebPage(this HttpContext httpContext)
		{
			if (httpContext == null)
				throw new InvalidOperationException("Code is running under not a web application.");

			return httpContext.Request.Url.Segments.Length > 0 ? Regex.Replace(httpContext.Request.Url.Segments[httpContext.Request.Url.Segments.Length - 1], @"^/?(.*?)/?$", "$1") : String.Empty;
		}

		public static string GetAbsolutePath(this  HttpContext httpContext, String relativePath)
		{
			if (relativePath == null)
				throw new ArgumentNullException("relativePath");
			if (httpContext == null)
				throw new InvalidOperationException("Code is running under not a web application.");

			return string.Format("{0}{1}", httpContext.Request.Url.GetLeftPart(UriPartial.Authority), relativePath);
		}
	}
}
