using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
namespace SelectPdf.Samples
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            // Apply the DenyLocalFileAccess flag from Web.config globally.
            // When true, SelectPdf rejects any attempt to convert local files / file:// URLs.
            bool deny;
            bool.TryParse(ConfigurationManager.AppSettings["DenyLocalFileAccess"], out deny);
            global::SelectPdf.GlobalProperties.ForceDenyLocalFileAccess = deny;

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

        // "Working …" button support. The sample actions convert on a POST whose
        // response is a PDF/image DOWNLOAD — which does NOT navigate the page, so
        // the page's sample-form.js can't tell when the work is done. It sends a
        // one-time "spdfDownloadToken" form field; here we echo it back as a cookie
        // ON the download response, so the JS poll knows the file was delivered and
        // restores the button. Only acts on actual downloads carrying the token
        // (static files / page renders untouched), so all convert actions get it
        // with no per-controller code.
        protected void Application_PreSendRequestHeaders(object sender, EventArgs e)
        {
            HttpContext ctx = HttpContext.Current;
            if (ctx == null) return;

            HttpResponse resp = ctx.Response;
            string ct = resp.ContentType ?? string.Empty;
            bool isDownload =
                ct.StartsWith("application/pdf", StringComparison.OrdinalIgnoreCase) ||
                ct.StartsWith("image/", StringComparison.OrdinalIgnoreCase) ||
                ct.StartsWith("application/octet-stream", StringComparison.OrdinalIgnoreCase);
            if (!isDownload) return;

            string token = ctx.Request.Form["spdfDownloadToken"];
            if (string.IsNullOrEmpty(token)) return;

            HttpCookie cookie = new HttpCookie("spdfDownloadToken", token);
            cookie.Path = "/";
            cookie.HttpOnly = false;                  // the page's JS must read it
            cookie.Expires = DateTime.UtcNow.AddSeconds(30);
            resp.Cookies.Add(cookie);
        }
    }
}
