using LHDN.CRM.WebAPI;
using LHDN.CRM.BC.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
using LHDN.CRM.Web.Filters;
using System.Security.Principal;
using System.Web.Caching;
using LHDN.CRM.Models.ViewModels;
using System.Web.Security;
using LHDN.CRM.BC;
using System.Web.Optimization;

namespace LHDN.CRM.Web
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            WebApiConfig.Init();
        }

        //void Session_Start(object sender, EventArgs e)
        //{
        //    if (Context.User != null)
        //    {
        //        HttpContext.Current.User = User;
        //    }
        //}

        protected void Application_AuthenticateRequest(Object sender, EventArgs e)
        {

            if (HttpContext.Current.User != null)
            {
                if (HttpContext.Current.User.Identity.IsAuthenticated)
                {
                    var url = HttpContext.Current.Request.Url;
                    if (!url.AbsolutePath.Contains("Error") && !IsWebAPIRequest())
                    {
                        UserProfileService userSvc = new UserProfileService();
                        userSvc.GetUserByLoginID();
                    }
                }
            }
        }


        //public void WindowsAuthentication_OnAuthenticate(object sender, WindowsAuthenticationEventArgs args)
        //{
        //    if (!args.Identity.IsAnonymous)
        //    {
        //        HttpContext.Current.Response.Redirect("~/Error/AccessDenied");
        //    }
        //    else {
        //        if (!HttpContext.Current.User.Identity.IsAuthenticated)
        //        {
        //            HttpContext.Current.Response.Redirect("~/Error/AccessDenied");
        //        }
        //    }
        //}

        protected void Application_Error(object sender, EventArgs e)
        {
            Exception ex = HttpContext.Current.Server.GetLastError();

            if (!IsWebAPIRequest())
            {
                RedirectPageByException(ex);
            }
        }

        #region Private

        public bool IsWebAPIRequest()
        {
            return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith("~/api");
        }

        private void RedirectPageByException(Exception ex)
        {
            if (ex is UnauthorizedAccessException || ex is PageAccessUnauthorizedException || ex is SystemAccessUnauthorizedException)
            {
                HttpContext.Current.Response.Redirect("~/Error/AccessDenied");
            }
            else if (ex is NotFoundException)
            {
                HttpContext.Current.Response.Redirect("~/Error/NotFound");
            }
            else if (ex is HttpException)
            {
                RedirectPageByHttpException((HttpException)ex);
            }
            else
            {
                HttpContext.Current.Response.Redirect("~/Error");
            }
        }

        private void RedirectPageByHttpException(HttpException ex)
        {
            int intStatusCode = ex.GetHttpCode();
            string strRedirectUrl = "/";

            switch (intStatusCode)
            {
                case 401:
                case 403:
                    strRedirectUrl = "~/Error/AccessDenied";
                    break;
                case 404:
                    strRedirectUrl = "~/Error/NotFound";
                    break;
                default:
                    strRedirectUrl = "~/Error";
                    break;
            }
            HttpContext.Current.Response.Redirect(strRedirectUrl);
        }
        #endregion
    }
}
