using System;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace StubCore.Plugins.Routing
{
    public class ProfileRouting : MvcRouteHandler
    {

        protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
        {

            var _route = new RoutingOperations();
            var reference = _route.GetProfileReference(requestContext.RouteData.Values["reference"].ToString());

            if (reference != null)
            {
                FillRequest(requestContext.RouteData.Values["controller"].ToString(),
                    requestContext.RouteData.Values["action"].ToString(),
                    reference,
                    requestContext);

               return new RedirectHandler(requestContext.RouteData.Values["controller"].ToString() + "/" + requestContext.RouteData.Values["action"].ToString() + "/" + reference);
            }

            return base.GetHttpHandler(requestContext);
        }

        public class RedirectHandler : IHttpHandler
        {
            private string newUrl;

            public RedirectHandler(string newUrl)
            {
                this.newUrl = newUrl;
            }

            public bool IsReusable
            {
                get { return true; }
            }

            public void ProcessRequest(HttpContext httpContext)
            {
                httpContext.Response.Status = "301 Moved Permanently";
                httpContext.Response.StatusCode = 301;
                httpContext.Response.AppendHeader("Location", newUrl);
                return;
            }
        }

        private static void FillRequest(string controller, string action, string id, RequestContext requestContext)
        {
            if (requestContext == null)
            {
                throw new ArgumentNullException("requestContext");
            }

            requestContext.RouteData.Values["controller"] = controller;
            requestContext.RouteData.Values["action"] = action;
            requestContext.RouteData.Values["reference"] = id;
        }

    }
}
