using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Aspose.Pdf;
using Aspose.Email;
using Microsoft.AspNetCore.Http.Features;
using Aspose.Email.Mime;
using Aspose.Cells.Rendering;
using SaveOptions = Aspose.Email.SaveOptions;
using Syncfusion.Drawing;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf;
using Aspose.Cells;
using GemBox.Document;
using GemBox.Email;
using LoadOptions = GemBox.Document.LoadOptions;

namespace BlazorServerProject.Data
{
    [Route("api/[controller]")]
    public class SampleDataController : Controller
    {
        private Microsoft.AspNetCore.Hosting.IHostingEnvironment hostingEnv;
        public IActionResult Index()
        {
            return View();
        }

        public SampleDataController(Microsoft.AspNetCore.Hosting.IHostingEnvironment env)
        {
            this.hostingEnv = env;
        }

        //[HttpPost("[action]")]
        //public async void Save(IList<IFormFile> UploadFiles)
        //{
        //    try
        //    {
        //        foreach (var file in UploadFiles)
        //        {
        //            if (UploadFiles != null)
        //            {
        //                var filename = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
        //                filename = hostingEnv.WebRootPath + $@"\{filename}";
        //                if (!System.IO.File.Exists(filename))
        //                {
        //                    using (FileStream fs = System.IO.File.Create(filename))
        //                    {
        //                        file.CopyTo(fs);
        //                        fs.Flush();
        //                    }

        //                    ConvertEmailToPdf(filename);


        //                }
        //                else
        //                {
        //                    Response.Clear();
        //                    Response.StatusCode = 204;
        //                    Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File already exists.";
        //                }
        //            }
        //        }
        //        Response.Headers.Add("ID", "custom_ID"); // Assign the custom data in the response header.
        //    }
        //    catch (Exception e)
        //    {
        //        Response.Clear();
        //        Response.ContentType = "application/json; charset=utf-8";
        //        Response.StatusCode = 204;
        //        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "No Content";
        //        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
        //    }

        //}

        //[HttpPost("Save")]

        //public async Task Save(IList<IFormFile> chunkFile, IList<IFormFile> UploadFiles)
        //{
        //    try
        //    {

        //        var test = HttpContext.Request.Form.Files["chunkFile"];

        //        var chunkIndex = HttpContext.Request.Form["chunk-index"];

        //        var totalChunk = HttpContext.Request.Form["total-chunk"];

        //        var chunkMetadata = HttpContext.Request.Form["ChunkMetaData"];

        //        if (chunkFile.Count > 0) //if we chunk upload
        //        {

        //            foreach (var file in chunkFile)
        //            {

        //                var filename = $"Appended - {file.FileName}";

        //                using Stream uploadStream = new MemoryStream();

        //                file.CopyTo(uploadStream);

        //                uploadStream.Flush();

        //                uploadStream.Position = 0;

        //               // how to catch exception from blob?? AND pause uploading

        //                await blobService.UploadFileToBlobAsync(uploadStream, filename);

        //            }

        //        }
        //        else // if we are uploading a file lower in size than chunk size it comes through the UploadFiles list
        //        {
        //            foreach (var file in UploadFiles)
        //            {

        //                var filename = $"{file.FileName}";

        //                using Stream uploadStream = new MemoryStream();

        //                file.CopyTo(uploadStream);

        //                uploadStream.Flush();

        //                uploadStream.Position = 0;
        //                // this may need a different handling of how we upload to blob?
        //                await blobService.UploadFileToBlobAsync(uploadStream, filename);

        //            }

        //        }
        //    }

        //    catch (Exception e)
        //    {

        //        Response.Clear();

        //        Response.StatusCode = 400;

        //        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File failed to upload";

        //        Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;

        //        Response.Headers.Add("ID", "Maximum Uploaded files reached");
        //    }

        //}

        [HttpPost("[action]")]
        public void Save(IList<IFormFile> chunkFile, IList<IFormFile> UploadFiles)
        {
            try
            {
                foreach (var file in chunkFile)
                {
                    var filename = hostingEnv.ContentRootPath + $@"\{file.FileName}";
                    if (!System.IO.File.Exists(filename))
                    {
                        using (FileStream fs = System.IO.File.Create(filename))
                        {
                            file.CopyTo(fs);
                            fs.Flush();
                        }
                    }
                    else
                    {
                        using (FileStream fs = System.IO.File.Open(filename, FileMode.Append))
                        {
                            file.CopyTo(fs);
                            fs.Flush();
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Response.Clear();
                Response.StatusCode = 204;
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File failed to upload";
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
            }
        }


        private void ConvertEmailToPdf(string filePath)
        {
            try
            {

                //MailMessage message = MailMessage.Load(filePath);

                //// Convert the message to PDF.
                //string pdfFilePath = Path.ChangeExtension(filePath, ".pdf");
                //message.Save(pdfFilePath);
                

                //// Log success message
                //Console.WriteLine($"Successfully converted {filePath} to PDF: {pdfFilePath}");

            }
            catch (Exception ex)
            {
                throw new ApplicationException($"Failed to convert {filePath} to PDF: {ex.Message}");
            }
        }

        [HttpPost("[action]")]
        public void Remove(IList<IFormFile> UploadFiles)
        {
            try
            {
                var filename = hostingEnv.ContentRootPath + $@"\{UploadFiles[0].FileName}";
                if (System.IO.File.Exists(filename))
                {
                    System.IO.File.Delete(filename);
                }
            }
            catch (Exception e)
            {
                Response.Clear();
                Response.StatusCode = 200;
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = "File removed successfully";
                Response.HttpContext.Features.Get<IHttpResponseFeature>().ReasonPhrase = e.Message;
            }
        }

        public class DataService
        {
            public async Task<List<string>> GetIndustriesAsync()
            {
                // Simulate asynchronous data retrieval (replace with actual data fetching logic)
                await Task.Delay(1000);

                // Replace this with actual data retrieval logic, e.g., making an API call or querying a database
                return new List<string> { "Finance", "Technology", "Healthcare", "Manufacturing" };
            }
        }
    }
}