using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Kendo.Core.Export;

namespace Editor_MailMerge_and_Export.Controllers
{
    public class HomeController : Controller
    {
        private readonly IWebHostEnvironment _hostingEnvironment;

        public HomeController(IWebHostEnvironment environment)
        {
            this._hostingEnvironment = environment;
        }
        public override void OnActionExecuting(ActionExecutingContext context)
        {
            if (!string.IsNullOrEmpty(context.HttpContext.Request.Query["culture"]))
            {
                CultureInfo.DefaultThreadCurrentCulture = CultureInfo.DefaultThreadCurrentUICulture = new CultureInfo(context.HttpContext.Request.Query["culture"]);
            }
            base.OnActionExecuting(context);
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Export(EditorExportData data)
        {
            var settings = new EditorDocumentsSettings();
            settings.HtmlImportSettings.LoadImageFromUri += HtmlImportSettings_LoadImageFromUri;

            try
            {
                return EditorExport.Export(data, settings);
            }
            catch
            {
                return RedirectToAction("Index", "Home");
            }
        }

        private void HtmlImportSettings_LoadImageFromUri(object sender, Telerik.Windows.Documents.Flow.FormatProviders.Html.LoadImageFromUriEventArgs e)
        {
            var uri = e.Uri;
            var absoluteUrl = uri.StartsWith("http://") || uri.StartsWith("www.");

            if (!absoluteUrl)
            {
                var trimmedUri = uri.Trim().TrimStart(Path.AltDirectorySeparatorChar).Replace("aspnet-core" + Path.AltDirectorySeparatorChar.ToString(), "");
                var webRootPath = _hostingEnvironment.WebRootPath;
                var filePath = Path.Combine(webRootPath, trimmedUri);

                using (var fileStream = System.IO.File.OpenRead(filePath))
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        fileStream.CopyTo(memoryStream);
                        e.SetImageInfo(memoryStream.ToArray(), "png");
                    }
                }
            }
        }
        public IActionResult About()
        {
            ViewData["Message"] = "Your application description page.";

            return View();
        }

        public IActionResult Contact()
        {
            ViewData["Message"] = "Your contact page.";

            return View();
        }

        public IActionResult Error()
        {
            return View();
        }
    }
}
