using System;
using System.Configuration;
using System.Web;
using SelectPdf;

namespace SelectPdf.Samples
{
    public class Global : System.Web.HttpApplication
    {
        protected void Application_Start(object sender, EventArgs e)
        {
            // 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);
            GlobalProperties.ForceDenyLocalFileAccess = deny;
        }

        // "Working …" button support. The sample pages convert on a postback 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. Fires for every response, but only acts on actual
        // downloads carrying the token (so static files / normal page renders are
        // untouched). Set here (just before headers flush) rather than per handler
        // so it works for all ~30 convert pages with no per-page 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);
        }
    }
}
