using System;
using System.Globalization;
using System.Threading;
using System.Web;
using System.Web.Helpers;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using System.Diagnostics;
using System.Web.Configuration;

namespace atakanozbancom
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            var mk = WebConfigurationManager.GetSection("system.web/machineKey")
         as MachineKeySection;

            Debug.WriteLine(
                $"[MK] validation={mk.Validation}, decryption={mk.Decryption}, " +
                $"validationKeyLen={mk.ValidationKey?.Length}, decryptionKeyLen={mk.DecryptionKey?.Length}"
            );

            // your existing stuff...
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

        }

        protected void Application_BeginRequest()
        {
            var lang = (HttpContext.Current.Request.RequestContext.RouteData.Values["lang"] as string)
                       ?? HttpContext.Current.Request.Cookies["culture"]?.Value
                       ?? "en";

            try
            {
                var ci = CultureInfo.CreateSpecificCulture(lang);
                Thread.CurrentThread.CurrentCulture = ci;
                Thread.CurrentThread.CurrentUICulture = ci;

                HttpContext.Current.Response.Cookies.Add(new HttpCookie("culture", ci.Name)
                {
                    Expires = DateTime.Now.AddYears(1),
                    HttpOnly = true
                });
            }
            catch
            {
                var fallback = CultureInfo.CreateSpecificCulture("en");
                Thread.CurrentThread.CurrentCulture = fallback;
                Thread.CurrentThread.CurrentUICulture = fallback;
            }
        }
    }
}
