using Elmah;
using FluentScheduler;
using Sevomin.Models;
using Sevomin.Models.Helpers;
using Sevomin.WebFrontend.Controllers;
using System;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Sevomin.WebFrontend
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            RouteConfig.RegisterRoutes(RouteTable.Routes);

#if !DEBUG
            TaskManager.Initialize(new SevominRegistry());
#endif
        }

        

        void ErrorLog_Filtering(object sender, ExceptionFilterEventArgs e)
        {
            if ((e.Exception.GetBaseException() is HttpException
                && ((HttpException)(e.Exception.GetBaseException())).GetHttpCode() == 404
                && e.Context is HttpContext)
                || ((HttpContext)e.Context).Request.Url.ToString().ToLower().Contains(@"favicon.ico".ToLower()))
            {
                e.Dismiss();
            }
        }

        static void TaskManager_UnobservedTaskException(Task sender, UnhandledExceptionEventArgs e)
        {
            var error = new Elmah.Error(e.ExceptionObject as Exception);

            Elmah.ErrorLog.GetDefault(System.Web.HttpContext.Current).Log(error);
        }

        protected void Application_EndRequest()
        {
            if (Context.Response.StatusCode == 404)
            {
                Response.Clear();

                var rd = new RouteData();                
                rd.Values["controller"] = "Base";
                rd.Values["action"] = "Error404";

                IController c = new BaseController();
                c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
            }
        }
    }
}
