using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using EVCB_OCPP.WEBAPI;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Configuration;

namespace EVCB_OCPP.WEBAPI.Controllers
{
    [ApiExplorerSettings(IgnoreApi = true)]
    [Route("file")]
    public class FileController : ControllerBase
    {
        private readonly FileExtensionContentTypeProvider typeProvider;
        //private readonly IWebHostEnvironment webHostEnvironment;
        private readonly ILogger<FileController> logger;
        private readonly string ftpPath;

        public FileController(
            FileExtensionContentTypeProvider typeProvider,
            //IWebHostEnvironment webHostEnvironment,
            IConfiguration configuration,
            ILogger<FileController> logger)
        {
            this.typeProvider = typeProvider;
            //this.webHostEnvironment = webHostEnvironment;
            this.logger = logger;

            this.ftpPath = "/home/UploadFiles/Diagnostics";
            if (!string.IsNullOrEmpty(configuration["FtpPath"]))
            {
                this.ftpPath = configuration["FtpPath"];
            }
        }

        [HttpPut]
        [HttpPost]
        public async Task<IActionResult> Upload()
        {

            var ctx = HttpContext;// HttpContextHelper.Current;
            //var root = ctx.Server.MapPath("~/UploadFiles/Diagnostics");
            //string root = string.Format("{webHostEnvironment.ContentRootPath}/UploadFiles/Diagnostics");

            if (!Directory.Exists(ftpPath))
            {
                Directory.CreateDirectory(ftpPath);
            }

            //var provider = new MultipartFileStreamProvider(root);

            try
            {
                if (!Request.HasFormContentType)
                //if (!Request.Content.IsMimeMultipartContent())
                {
                    //throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                    return StatusCode(StatusCodes.Status415UnsupportedMediaType);
                }

                //await Request.Content.ReadAsMultipartAsync(provider);

                foreach (IFormFile file in Request.Form.Files)
                {
                    if (file.Headers.ContentType.Contains("application/zip"))
                    {
                        var name = file.FileName;
                        name = name.Trim('"');

                        //var localFileName = file.LocalFileName;
                        var filePath = Path.Combine(ftpPath, name);
                        if (!System.IO.File.Exists(filePath))
                        {
                            //System.IO.File.Move(localFileName, filePath);
                            using (var istream = file.OpenReadStream())
                            using (var fstream = System.IO.File.Open(filePath, FileMode.CreateNew))
                            {
                                await istream.CopyToAsync(fstream);
                            }
                        }
                        else
                        {
                            //return Request.CreateResponse(HttpStatusCode.BadRequest);
                            return StatusCode(StatusCodes.Status400BadRequest);
                        }
                    }
                    else
                    {
                        //return Request.CreateResponse(HttpStatusCode.Forbidden);
                        return StatusCode(StatusCodes.Status403Forbidden);
                    }
                }

                //foreach (var file in provider.FileData)
                //{
                //    if (file.Headers.ContentType.MediaType == "application/zip")
                //    {
                //        var name = file.Headers.ContentDisposition.FileName;
                //        name = name.Trim('"');

                //        var localFileName = file.LocalFileName;
                //        var filePath = Path.Combine(root, name);
                //        if (!System.IO.File.Exists(filePath))
                //        {
                //            System.IO.File.Move(localFileName, filePath);
                //        }
                //        else
                //        {
                //            //return Request.CreateResponse(HttpStatusCode.BadRequest);
                //            return StatusCode(StatusCodes.Status400BadRequest);
                //        }
                //    }
                //    else
                //    {
                //        //return Request.CreateResponse(HttpStatusCode.Forbidden);
                //        return StatusCode(StatusCodes.Status403Forbidden);
                //    }
                //}
                //return Request.CreateResponse(HttpStatusCode.OK);
                return StatusCode(StatusCodes.Status200OK);
            }
            catch (Exception ex)
            {
                logger.LogError(ex.Message);
                logger.LogError(ex.StackTrace);
                //return Request.CreateResponse(HttpStatusCode.InternalServerError, ex.ToString());
                return StatusCode(StatusCodes.Status500InternalServerError, ex.ToString());
            }


        }

        [HttpGet("{FileName}")]
        public IActionResult GetFile([FromRoute] string FileName)
        {
            try
            {

                //string root = string.Format($"{webHostEnvironment.ContentRootPath}/UploadFiles/Diagnostics");
                var filePath = Path.Combine(ftpPath, FileName);

                if (!FileName.ToLower().EndsWith(".zip") ||
                    !System.IO.File.Exists(filePath))
                {
                    return StatusCode(StatusCodes.Status400BadRequest);
                }

                var stream = System.IO.File.OpenRead(filePath);
                if (!typeProvider.TryGetContentType(FileName, out var contentType))
                {
                    return StatusCode(StatusCodes.Status500InternalServerError);
                }
                //return new FileStreamResult(stream, "application/zip");
                return File(stream, contentType, fileDownloadName: FileName, enableRangeProcessing: false);
            }
            catch (Exception e)
            {
                logger.LogError(e.Message);
                logger.LogError(e.StackTrace);
                return null;
            }
        }
    }
}
