using ASP.Back.Libraries;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using System.Security.Principal;
using TeamManiacs.Core.Models;
using TeamManiacs.Data;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace ASP.Back.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ProfilePictureController : ControllerBase
    {
        private readonly TeamManiacsDbContext _context;
        private MediaManager _mediaManager;
        private StreamOut streamOut;
        public ProfilePictureController(TeamManiacsDbContext context, MediaManager mediaManager)
        {
            _context = context;
            _mediaManager = mediaManager;
            streamOut = new StreamOut(this);
        }


        // GET api/<ProfilePictureController>/5
        [Authorize]
        [HttpGet("{id}")]
        public async Task Get(int id)
        {
            Response.StatusCode = 400;
            try
            {
                if (this.User.Identity == null)
                {
                    Response.StatusCode = 401;
                    return;
                }
                Users user = await ControllerHelpers.GetUserById(id, _context);
                if (user == null)
                {
                    Response.StatusCode = 400;
                    return;
                }

                using (FileStream indexStream = _mediaManager.GetMedia(MediaManager.MediaType.ProfilePic, id.ToString()) as FileStream)
                {
                    if (indexStream != null && indexStream.Length > 0)
                    {
                        TeamManiacs.Core.Enums.MediaFormat? mediaFormat = await ControllerHelpers.GetProfilePictureContentTypeByUserId(id, _context);
                        if (mediaFormat == null)
                        {
                            Response.StatusCode = 400;
                            indexStream.Close();
                            return;
                        }
                        string contentType = _mediaManager.MediaFormatToString(mediaFormat.Value);
                        await streamOut.Write(indexStream, contentType, StreamOut.StatusCodes.Blob);
                        indexStream.Close();
                    }
                    if (streamOut.StatusCode == 400)
                    {
                        await streamOut.Write($"ProfilePicture.GET: Bad Request");
                        return;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                Response.StatusCode = 500;
                return;
            }
            return ;
        }

        // POST api/<ProfilePictureController>
        [Authorize]
        [HttpPost]
        public async Task< IActionResult> Post([FromForm] UploadPicture picture)
        {
            try
            {
                if (this.User.Identity == null)
                {
                    return BadRequest();
                }
                var userId = ControllerHelpers.GetUserIdFromToken(this.User.Identity);
                if (userId == null)
                {
                    return BadRequest();
                }
                if(picture.Picture.Length/1024 > 1024 * 11) {
                    return BadRequest("Picture Too Large! Please stay under " + 1024 * 11 + " bytes");
                }

                if (!_mediaManager.UploadProfilePicture(userId.Value, picture.Picture))
                {
                    return BadRequest("Failed To Upload!");
                }
                Users user = await ControllerHelpers.GetUserById(userId.Value, _context);

                if (user == null) {
                    _mediaManager.DeleteProfilePicture(userId.Value);
                    return BadRequest("Failed To Upload!");
                }

                Picture pPicture = new Picture();
                pPicture.MediaFormat = _mediaManager.StringToMediaFormat(picture.Picture.ContentType).Value;
                pPicture.Name = Path.GetFileName(picture.Picture.FileName);               

                await _context.ProfilePicture.AddAsync(pPicture);
                await _context.SaveChangesAsync();

                
                user.ProfilePicture = pPicture.Id;
                await _context.SaveChangesAsync();
                return Ok("Successfully Uploaded Your Image!");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return BadRequest();
            }
            }

        // PUT api/<ProfilePictureController>/5
        [Authorize]
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/<ProfilePictureController>/5
        [Authorize]
        [HttpDelete("{id}")]
        private void Delete(int id)
        {
        }
    }
}
