using System;
using System.Configuration;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Routing;
namespace SelectPdf.Samples
{
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801
    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();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }

        // "Working …" button support. The convert action's response is a PDF/image
        // DOWNLOAD, which doesn't 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 restores the button. Only acts on downloads carrying the token.
        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);
        }
    }
}