using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using System;
using System.IO;
using System.Threading.Tasks;

namespace RadzenBlazorDemos
{
    [DisableRequestSizeLimit]
    public partial class UploadController : Controller
    {
        private readonly IWebHostEnvironment environment;

        public UploadController(IWebHostEnvironment environment)
        {
            this.environment = environment;
        }

        [HttpPut("api/upload/stream")]
        public async Task<IActionResult> Stream()
        {
            try
            {
                // Put your code here
                
                using (var ms = new MemoryStream())
                {
                    await Request.Body.CopyToAsync(ms);
                    byte[] fileBytes = ms.ToArray();
                    
                    return Ok(new { Completed = true, fileSize = fileBytes.Length });
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }
        
        [HttpPost("api/upload/single")]
        public IActionResult Single(IFormFile file)
        {
            try
            {
                // Put your code here
                return Ok(new { Completed = true });
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }

        [HttpPost("api/upload/image")]
        public IActionResult Image(IFormFile file)
        {
            try
            {
                // Used for demo purposes only
                DeleteOldFiles();

                var fileName = $"upload-{DateTime.Today.ToString("yyyy-MM-dd")}-{Guid.NewGuid()}{Path.GetExtension(file.FileName)}";

                using (var stream = new FileStream(Path.Combine(environment.WebRootPath, fileName), FileMode.Create))
                {
                    // Save the file
                    file.CopyTo(stream);

                    // Return the URL of the file
                    var url = Url.Content($"~/images/{fileName}");

                    return Ok(new { Url = url });
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }

        void DeleteOldFiles()
        {
            foreach (var file in Directory.GetFiles(environment.WebRootPath))
            {
                var fileName = Path.GetFileName(file);

                if (fileName.StartsWith("upload-") && !fileName.StartsWith($"upload-{DateTime.Today.ToString("yyyy-MM-dd")}"))
                {
                    try
                    {
                        System.IO.File.Delete(file);
                    }
                    catch
                    {

                    }
                }
            }
        }

        [HttpPost("api/upload/multiple")]
        public IActionResult Multiple(IFormFile[] files)
        {
            try
            {
                // Put your code here
                return StatusCode(200);
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }

        [HttpPost("api/upload/custom-header")]
        public IActionResult CustomHeader(IFormFile file)
        {
            try
            {
                var uploadedBy = Request.Headers["X-Uploaded-By"].ToString();
                var authorization = Request.Headers["Authorization"].ToString();

                return Ok(new { uploadedBy, authorization});
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }

        [HttpPost("api/upload/{id}")]
        public IActionResult Post(IFormFile[] files, int id, [FromQuery] string query)
        {
            try
            {
                return Ok(new { id, query});
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }

        [HttpPost("api/upload/specific")]
        public IActionResult Specific(IFormFile myName)
        {
            try
            {
                // Put your code here
                return Ok(new { Completed = true });
            }
            catch (Exception ex)
            {
                return StatusCode(500, ex.Message);
            }
        }
    }
}