using System;
using System.Collections.Generic;
using System.Web.Mvc;
using System.Configuration;
using SelectPdf;

namespace SelectPdf.Samples.Controllers
{
    public class ConvertFromJsController : Controller
    {
        // GET: ConvertFromJs
        public ActionResult Index()
        {
            string url = System.Web.VirtualPathUtility
                .ToAbsolute("~/files/js-conversion.html");
            ViewData.Add("ViewTxtUrl", (new Uri(Request.Url, url)).AbsoluteUri);

            ViewData.Add("ViewTxtHref", url);
            ViewData.Add("ViewDdlStartupModeSel", "Manual");
            
            List<SelectListItem> DdlStartupMode = new List<SelectListItem>();
            DdlStartupMode.Add(new SelectListItem
            {
                Text = "Automatic",
                Value = "Automatic",
                Selected = ViewData["ViewDdlStartupModeSel"] != null && 
                    ViewData["ViewDdlStartupModeSel"].ToString() == "Automatic"
            });
            DdlStartupMode.Add(new SelectListItem
            {
                Text = "Manual",
                Value = "Manual",
                Selected = ViewData["ViewDdlStartupModeSel"] != null && 
                    ViewData["ViewDdlStartupModeSel"].ToString() == "Manual"
            });
            ViewData.Add("ViewDdlStartupMode", DdlStartupMode);
            return View();
        }

        [HttpPost]
        public ActionResult SubmitAction(FormCollection collection)
        {
            RenderingEngine renderingEngine =
                (RenderingEngine)Enum.Parse(typeof(RenderingEngine), Request["DdlRenderingEngine"], true);

            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();
            converter.Options.RenderingEngine = renderingEngine;
            converter.Options.CefEnginePath = Server.MapPath(ConfigurationManager.AppSettings["CefEnginePath"]);

            // set startup mode
            converter.Options.StartupMode = (HtmlToPdfStartupMode)Enum.Parse(
                typeof(HtmlToPdfStartupMode), collection["DdlStartupMode"], true);

            // set timeout
            int timeout = 10;
            try
            {
                timeout = Convert.ToInt32(collection["TxtTimeout"]);
            }
            catch { }
            converter.Options.MaxPageLoadTime = timeout;

            // create a new pdf document converting an url
            PdfDocument doc = converter.ConvertUrl(collection["TxtUrl"]);

            // save pdf document
            byte[] pdf = doc.Save();

            // close pdf document
            doc.Close();

            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            fileResult.FileDownloadName = "Document.pdf";
            return fileResult;
        }   
    }
}