using Exsersewo.Common.Utilities;
using Kynareth.Attributes;
using Kynareth.Helpers;
using Kynareth.Managers;
using Kynareth.Models;
using Microsoft.AspNetCore.Mvc;

namespace Kynareth.Controllers;

[Route("image/manipulation")]
public class ImageManipulationController : BaseController<ImageManipulationController>
{
	public ImageManipulationController(IConfiguration configuration, ILoggerFactory loggerFactory, IWebHostEnvironment appEnvironment) : base(configuration, loggerFactory, appEnvironment)
	{ }
	
	/// ---------- ///
	/// MAGIK      ///
	/// ---------- ///
	[HttpGet("magik")]
	[EndpointMetrics("image.manipulation.magik")]
	[ProducesResponseType(typeof(Stream), StatusCodes.Status200OK, "image/png")]
	[ProducesResponseType(typeof(Stream), StatusCodes.Status200OK, "image/gif")]
	[ProducesResponseType(typeof(EventResult), StatusCodes.Status400BadRequest)]
	[ProducesResponseType(typeof(EventResult), StatusCodes.Status500InternalServerError)]
	public async Task<object> MagikImage([FromQuery] string image)
	{
		try
		{
			if (!string.IsNullOrWhiteSpace(image))
			{
				var (data, contentType) = await ImageManager.GetLiquidRescaledImageAsync(image);
				
				return HttpContext.SendStream(data, contentType);
			}

			return HttpContext.Send(EventResult.FromFailure("No image has been provided"), System.Net.HttpStatusCode.BadRequest);
		}
		catch (ArgumentException ex)
		{
			_logger.LogCritical(ex.Message, ex);
			
			return HttpContext.Send(EventResult.FromFailure("Can't parse result"), System.Net.HttpStatusCode.InternalServerError);
		}
	}
	
	/// ------------- ///
	///   TOP  TEXT   ///
	///               ///
	///  BOTTOM TEXT  ///
	/// ------------- ///
	[HttpGet("{template}")]
	[EndpointMetrics("image.manipulation.generate")]
	[ProducesResponseType(typeof(Stream), StatusCodes.Status200OK, "image/png")]
	[ProducesResponseType(typeof(EventResult), StatusCodes.Status400BadRequest)]
	[ProducesResponseType(typeof(EventResult), StatusCodes.Status404NotFound)]
	[ProducesResponseType(typeof(EventResult), StatusCodes.Status500InternalServerError)]
	public async Task<object> GenerateMemeAsync(string template, [FromQuery] string[] text)
	{
		try
		{
			if (!string.IsNullOrWhiteSpace(template))
			{
				var result = await ImageManager.GenerateMemeImageAsync(template, text);

				if (result is byte[] data)
				{
					var image = new MemoryStream(data);
				
					return HttpContext.SendStream(image, "image/png");
				}

				return result as IResult;
			}

			return HttpContext.Send(EventResult.FromFailure("No template has been provided"), System.Net.HttpStatusCode.BadRequest);
		}
		catch (ArgumentException ex)
		{
			_logger.LogCritical(ex.Message, ex);
			
			return HttpContext.Send(EventResult.FromFailure("Can't parse result"), System.Net.HttpStatusCode.InternalServerError);
		}
	}
}