﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using arnvanhoutte.DataAccess.Interfaces;
using arnvanhoutte.Domain.Entities.File;
using ImageSharp;
using Microsoft.AspNetCore.Mvc;

namespace arnvanhoutte.Controllers.API
{
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class FileController : Controller
    {
        private readonly IFileRepository _blobRepo;
        public FileController(IFileRepository blobRepo)
        {
            //_blobRepo = new IFileRepository(config, "arnvanhoutte");
            _blobRepo = blobRepo;
        }

        [HttpPost("")]
        public async Task<IActionResult> Upload()
        {
            var files = Request.Form.Files;
            if (files.Count != 1) return BadRequest();
            var file = files.First();
            var filename = Guid.NewGuid().ToString();
            using (var stream = new MemoryStream())
            {
                var buffer = new byte[2048]; // read in chunks of 2KB
                int bytesRead;
                var fs = file.OpenReadStream();
                while ((bytesRead = await fs.ReadAsync(buffer, 0, buffer.Length)) > 0)
                {
                    stream.Write(buffer, 0, bytesRead);
                }
                var result = stream.ToArray();
                await _blobRepo.UploadNewBlob(result, filename, file.ContentType);
            }
            return Ok(new FileUploadReturn{Success = true,Url = $"https://arnvanhoutte.blob.core.windows.net/arnvanhoutte/{filename}" });
        }
        [HttpGet]
        [Route("/api/file")]
        public async Task<List<string>> Get()
        {
            return await _blobRepo.GetBlobsAsync();
        }

        private byte[] GetThumbnail(Image image)
        {
            using (var ms = new MemoryStream())
            {
                var heightRatio = 300 / image.Height;
                image.Resize(image.Width * heightRatio, 300).Save(ms);
                return ms.ToArray();
            }
        }
    }

    public class FileViewModel
    {
        public string Image { get; set; }
    }
}