using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using rockfishCore.Models;

namespace rockfishCore.Controllers
{
    [Produces("application/json")]
    [Route("api/RfCaseBlob")]
    public class RfCaseBlobController : Controller
    {
        private readonly rockfishContext _context;

        public RfCaseBlobController(rockfishContext context)
        {
            _context = context;
        }

        // GET: api/RfCaseBlob
        [HttpGet]
        [Authorize]
        public IEnumerable<RfCaseBlob> GetRfCaseBlob()
        {
            var c = from s in _context.RfCaseBlob select s;
            c = c.OrderBy(s => s.Name);
            return c;
        }



        [HttpPost("upload")]
        public IActionResult UploadFilesAjax([FromQuery] string rfcaseid)
        {//http://www.binaryintellect.net/articles/f1cee257-378a-42c1-9f2f-075a3aed1d98.aspx

            //need a proper case ID to do this
            if (string.IsNullOrWhiteSpace(rfcaseid) || rfcaseid == "new")
            {
                return BadRequest();
            }
       
            var files = Request.Form.Files;
            int nCount=0;
            foreach (var file in files)
            {
                if (file.Length > 0)
                {
                    using (var fileStream = file.OpenReadStream())
                    using (var ms = new System.IO.MemoryStream())
                    {
                        fileStream.CopyTo(ms);
                        var fileBytes = ms.ToArray();
                        RfCaseBlob blob=new RfCaseBlob();
                        blob.RfCaseId=Convert.ToInt64(rfcaseid);
                        blob.Name=file.FileName;
                        blob.File=fileBytes;
                        _context.RfCaseBlob.Add(blob);                        
                        _context.SaveChanges();                        
                        nCount++;
                    }
                }
            }

            string message = $"{nCount} file(s) uploaded successfully!";

            return Json(message);
        }




        [HttpGet("download/{id}")]
        public ActionResult Download([FromRoute] long id, [FromQuery] string dlkey)
        {//https://dotnetcoretutorials.com/2017/03/12/uploading-files-asp-net-core/
         //https://stackoverflow.com/questions/45763149/asp-net-core-jwt-in-uri-query-parameter/45811270#45811270

            if (string.IsNullOrWhiteSpace(dlkey))
            {
                return NotFound();
            }

            //get user by key, if not found then reject
            //If user dlkeyexp has not expired then return file
            var user = _context.User.SingleOrDefault(m => m.DlKey == dlkey);
            if (user == null)
            {
                return NotFound();
            }

            var unixdtnow = new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds();
            if (user.DlKeyExp < unixdtnow)
            {
                return NotFound();
            }

            //Ok, user has a valid download key and it's not expired yet so get the file
            var f = _context.RfCaseBlob.SingleOrDefault(m => m.Id == id);
            if (f == null)
            {
                return NotFound();
            }

            var extension = System.IO.Path.GetExtension(f.Name);

            string mimetype = "application/x-msdownload";
            if (!string.IsNullOrWhiteSpace(extension))
            {
                mimetype = Util.MimeTypeMap.GetMimeType(extension);
            }

            Response.Headers.Add("Content-Disposition", "inline; filename=" + f.Name);
            return File(f.File, mimetype);//NOTE: if you don't specify a filename here then the above content disposition header takes effect, if you do then the 'File(' method sets it as attachment automatically

        }


        // GET: api/RfCaseBlob/5
        [HttpGet("{id}")]
        [Authorize]
        public async Task<IActionResult> GetRfCaseBlob([FromRoute] long id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var RfCaseBlob = await _context.RfCaseBlob.SingleOrDefaultAsync(m => m.Id == id);

            if (RfCaseBlob == null)
            {
                return NotFound();
            }

            return Ok(RfCaseBlob);
        }

        // PUT: api/RfCaseBlob/5
        [HttpPut("{id}")]
        [Authorize]
        public async Task<IActionResult> PutRfCaseBlob([FromRoute] long id, [FromBody] RfCaseBlob RfCaseBlob)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != RfCaseBlob.Id)
            {
                return BadRequest();
            }

            _context.Entry(RfCaseBlob).State = EntityState.Modified;

            try
            {
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!RfCaseBlobExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return NoContent();
        }

        // POST: api/RfCaseBlob
        [HttpPost]
        [Authorize]
        public async Task<IActionResult> PostRfCaseBlob([FromBody] RfCaseBlob RfCaseBlob)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            _context.RfCaseBlob.Add(RfCaseBlob);
            await _context.SaveChangesAsync();

            return CreatedAtAction("GetRfCaseBlob", new { id = RfCaseBlob.Id }, RfCaseBlob);
        }

        // DELETE: api/RfCaseBlob/5
        [HttpDelete("{id}")]
        [Authorize]
        public async Task<IActionResult> DeleteRfCaseBlob([FromRoute] long id)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            var RfCaseBlob = await _context.RfCaseBlob.SingleOrDefaultAsync(m => m.Id == id);
            if (RfCaseBlob == null)
            {
                return NotFound();
            }

            _context.RfCaseBlob.Remove(RfCaseBlob);
            await _context.SaveChangesAsync();

            return Ok(RfCaseBlob);
        }

        private bool RfCaseBlobExists(long id)
        {
            return _context.RfCaseBlob.Any(e => e.Id == id);
        }
    }
}