using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Optimization;
using BeachOrder.App_Start;
using System.Web.Http;
using System.Data.SqlClient;
using ErsPos.Data.Model;
using BeachOrder.Helpers;

namespace BeachOrder
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {

            AreaRegistration.RegisterAllAreas();
            // Manually installed WebAPI 2.2 after making an MVC project.
            GlobalConfiguration.Configure(WebApiConfig.Register); // NEW way
            //WebApiConfig.Register(GlobalConfiguration.Configuration); // DEPRECATED

            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
            // BundleTable.Bundles.RegisterTemplateBundles();
            //FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            //GlobalFilters.Filters.Add(new BeachOrder.ActionFilters.LisansFilter());
            
        }

        protected void Application_BeginRequest()
        {
            //// cache den oku
            //var result = CacheHelper.ReadFromMemory("lisans");
            //// henuz memde bişey yoksa
            //if (result == null)
            //{
            //    // db den oku ve lisansız ise
            //    var lisansResult = Helpers.Helpers.LisansOku();
            //    if (lisansResult == Models.Lisans.Lisanssiz)
            //    {
            //        CacheHelper.SaveToMemory("lisans",Models.Lisans.Lisanssiz.ToSafeString(),1);

            //        // Uygulamada sayfa bulunamamış ise yönelendirme yap
            //        HttpContext.Current.RewritePath("~/License");
            //    }
            //    else
            //    {
            //        // lisanslı ise cache e 15 gün süre için yaz;
            //        CacheHelper.SaveToMemory("lisans", Models.Lisans.Lisansli.ToSafeString(), 15);
            //    }
            //}
        }

        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();
            Response.Clear();
            var url = Request.Url.AbsoluteUri;
            HttpException httpException = exception as HttpException;
            Server.ClearError();
            if (httpException != null)
            {
                // menu uygumalası için gelmiş olabilir mi ?
                if (url.ToLower().Contains("menu"))
                {
                    Response.Redirect("Menu");
                    //HttpContext.Current.RewritePath("~/Menu");
                }
                // değilse pos a git madem
                else
                {
                    //HttpContext.Current.RewritePath("~/");
                    Response.Redirect("/");
                }                
            }
        }
    }
}
