using Microsoft.AspNetCore.Mvc;
using Microsoft.Net.Http.Headers;
using PosterMaker.Interfaces.Services;
using PosterMaker.Models;
using PosterMaker.Models.Enums;

namespace PosterMaker.Controllers;

[ApiController]
[Route("poster")]
public class MagickController : Controller
{
    private readonly IMoviePosterMakerService _moviePosterMakerService;
    private readonly ILogger<MagickController> _logger;
    private readonly ICollectionPosterMakerService _collectionPosterMakerService;
    private readonly ISeriesPosterMakerService _seriesPosterMakerService;

    public MagickController(IMoviePosterMakerService moviePosterMakerService, ILogger<MagickController> logger,
        ICollectionPosterMakerService collectionPosterMakerService, ISeriesPosterMakerService seriesPosterMakerService)
    {
        _moviePosterMakerService = moviePosterMakerService;
        _logger = logger;
        _collectionPosterMakerService = collectionPosterMakerService;
        _seriesPosterMakerService = seriesPosterMakerService;
    }

    [HttpPost, DisableRequestSizeLimit]
    [RequestFormLimits(MultipartBodyLengthLimit = 268435456)]
    [Route("Movie")]
    public IActionResult Movie([FromForm]IFormFile image, 
        [FromForm]string? topSubtitle, 
        [FromForm]string? title, 
        [FromForm]string? subtitle, 
        [FromForm]string? index,
        [FromForm]string? title2,
        [FromForm]MovieLogoEnum? logo,
        [FromForm]LogoOptionEnum? logoOption)
    {
        _logger.LogInformation("Received information from FE: title: {Title}, title2: {Title2}, subtitle: {Subtitle}, index: {Index}, topSubtitle: {TopSubtitle}", title, title2, subtitle, index, topSubtitle);
        var imageProperties = new ImageProperties
        {
            Title = string.IsNullOrEmpty(title) || title == "undefined" ? "" : title,
            Subtitle = string.IsNullOrEmpty(subtitle) || subtitle == "undefined" ? "" : subtitle,
            TopSubtitle = string.IsNullOrEmpty(topSubtitle) || topSubtitle == "undefined" ? "" : topSubtitle,
            Index = string.IsNullOrEmpty(index) || index == "undefined" ? "" : index,
            Title2 = string.IsNullOrEmpty(title2) || title2 == "undefined" ? "" : title2,
            Logo = logo,
            LogoOption = logoOption
        };
        try
        {
            var folderName = Path.Combine("Resources", "Uploads");
            var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);

            if (image.Length <= 0) return BadRequest();
            var fileName = ContentDispositionHeaderValue.Parse(image.ContentDisposition).FileName.ToString();
            var fullPath = Path.Combine(pathToSave, fileName);
            var dbPath = Path.Combine(folderName, fileName);
            
            using (var stream = new FileStream(fullPath, FileMode.Create))
            {
                image.CopyTo(stream);
            }

            var response = _moviePosterMakerService.CreatePoster(dbPath, imageProperties);
            return Ok(new FileUploadResponse{PicBytes = Convert.ToBase64String(response)});

        }
        catch (Exception ex)
        {
            _logger.LogError("Unhandled error", ex);
            return StatusCode(500, $"Internal server error: {ex}");
        }
    }
    
    [HttpPost, DisableRequestSizeLimit]
    [RequestFormLimits(MultipartBodyLengthLimit = 268435456)]
    [Route("Collection")]
    public IActionResult Collection([FromForm]IFormFile image,
        [FromForm]string? title,
        [FromForm]string? title2,
        [FromForm]MovieLogoEnum? logo,
        [FromForm]LogoOptionEnum? logoOption)
    {
        _logger.LogInformation("Received information from FE: title: {Title}", title);
        var imageProperties = new ImageProperties
        {
            Title = string.IsNullOrEmpty(title) || title == "undefined" ? "" : title,
            Title2 = string.IsNullOrEmpty(title2) || title2 == "undefined" ? "" : title2,
            Logo = logo,
            LogoOption = logoOption
        };
        try
        {
            var folderName = Path.Combine("Resources", "Uploads");
            var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);

            if (image.Length <= 0) return BadRequest();
            var fileName = ContentDispositionHeaderValue.Parse(image.ContentDisposition).FileName.ToString();
            var fullPath = Path.Combine(pathToSave, fileName);
            var dbPath = Path.Combine(folderName, fileName);
            
            using (var stream = new FileStream(fullPath, FileMode.Create))
            {
                image.CopyTo(stream);
            }

            var response = _collectionPosterMakerService.CreatePoster(dbPath, imageProperties);
            return Ok(new FileUploadResponse{PicBytes = Convert.ToBase64String(response)});

        }
        catch (Exception ex)
        {
            _logger.LogError("Unhandled error", ex);
            return StatusCode(500, $"Internal server error: {ex}");
        }
    }
    
    [HttpPost, DisableRequestSizeLimit]
    [RequestFormLimits(MultipartBodyLengthLimit = 268435456)]
    [Route("Series")]
    public IActionResult Series([FromForm]IFormFile image,
        [FromForm]string? title,
        [FromForm]string? title2,
        [FromForm]string? season,
        [FromForm]string? subtitle,
        [FromForm]string? topSubtitle,
        [FromForm]MovieLogoEnum? logo,
        [FromForm]LogoOptionEnum? logoOption,
        [FromForm]NetworkLogoEnum? networkLogo,
        [FromForm]bool? limitedSeries)
    {
        _logger.LogInformation("Received information from FE: title: {Title}", title);
        var imageProperties = new ImageProperties
        {
            Title = string.IsNullOrEmpty(title) || title == "undefined" ? "" : title,
            Title2 = string.IsNullOrEmpty(title2) || title2 == "undefined" ? "" : title2,
            Logo = logo,
            LogoOption = logoOption,
            NetworkLogo = networkLogo,
            Season = string.IsNullOrEmpty(season) || season == "undefined" ? "" : season,
            Subtitle = string.IsNullOrEmpty(subtitle) || subtitle == "undefined" ? "" : subtitle,
            TopSubtitle = string.IsNullOrEmpty(topSubtitle) || topSubtitle == "undefined" ? "" : topSubtitle,
            LimitedSeries = limitedSeries
        };
        try
        {
            var folderName = Path.Combine("Resources", "Uploads");
            var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);

            if (image.Length <= 0) return BadRequest();
            var fileName = ContentDispositionHeaderValue.Parse(image.ContentDisposition).FileName.ToString();
            var fullPath = Path.Combine(pathToSave, fileName);
            var dbPath = Path.Combine(folderName, fileName);
            
            using (var stream = new FileStream(fullPath, FileMode.Create))
            {
                image.CopyTo(stream);
            }

            var response = _seriesPosterMakerService.CreatePoster(dbPath, imageProperties);
            return Ok(new FileUploadResponse{PicBytes = Convert.ToBase64String(response)});

        }
        catch (Exception ex)
        {
            _logger.LogError("Unhandled error", ex);
            return StatusCode(500, $"Internal server error: {ex}");
        }
    }
}