using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;

namespace wispro.sp.api.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    //[Authorize]
    public class FileProcesTaskController : ControllerBase
    {
        Services.IFileTaskService fileTaskService;

        public FileProcesTaskController(Services.IFileTaskService _fileTaskService)
        {
            fileTaskService = _fileTaskService;
        }

        public share.FileProcessTask Get(string Id)
        {
            return fileTaskService.Get(Id);
        }

        [HttpGet, DisableRequestSizeLimit]
        public async Task<IActionResult> Download(string Id)
        {
            
            var filename = fileTaskService.Get(Id);

            if (filename != null)
            {
                var attachfileSavePath = utility.ConfigHelper.GetSectionValue("AttachFileSavePath");
                var filePath = filename.FilePath;

                var context = HttpContext;

                if (System.IO.File.Exists(filePath))
                {
                    var memory = new MemoryStream();
                    await using (var stream = new FileStream(filePath, FileMode.Open))
                    {
                        await stream.CopyToAsync(memory);
                    }
                    memory.Position = 0;
                    return File(memory, GetContentType(filename.FilePath), filename.FileName);
                }
                else
                    return NotFound();
            }
            else
            {
                return NotFound();
            }
        }

        private string GetContentType(string path)
        {
            var provider = new FileExtensionContentTypeProvider();
            string contentType;

            if (!provider.TryGetContentType(path, out contentType))
            {
                contentType = "application/octet-stream";
            }

            return contentType;
        }
    }
}
