using System.Text;
using Exsersewo.Common.Utilities;
using ImageMagick;
using Kynareth.Models;

namespace Kynareth.Managers;

public static partial class ImageManager
{
	private static List<ImageManipulationImage> ManipulationEndpoints;

	private static string ManipulationTemplateBaseFolder;
	
	static void ConfigureManipulation(IConfiguration configuration, IWebHostEnvironment _appEnvironment)
	{
		ManipulationTemplateBaseFolder = Path.Combine(_appEnvironment.WebRootPath, configuration.GetValue<string>("ImageManipulation:Folder"));
		ManipulationEndpoints = configuration.GetSection("ImageManipulation:Templates").Get<List<ImageManipulationImage>>();
	}

	public static async Task<object> GenerateMemeImageAsync(string template, string[] texts)
	{
		ImageManipulationImage imageTemplate = ManipulationEndpoints.FirstOrDefault(e => e.Name.ToLowerInvariant().Equals(template.ToLowerInvariant()));
				
		if (imageTemplate is null)
		{
			var ex = new ArgumentException($"Couldn't find endpoint named \"{template}\"", nameof(template));

			return GetResult(StatusCodes.Status404NotFound, EventResult.FromFailureException(ex.Message, ex));
		}

		if (imageTemplate.TextPositions.Count > texts.Length)
		{
			var ex = new ArgumentException("Not enough texts provided", nameof(texts));

			return GetResult(StatusCodes.Status400BadRequest, EventResult.FromFailureException(ex.Message, ex));
		}

		string image = Path.Combine(ManipulationTemplateBaseFolder, imageTemplate.Image);
			
		using MagickImage templateImage = new(File.ReadAllBytes(image));
		using MagickImage baseImage = new(MagickColors.Transparent, templateImage.Width, templateImage.Height);

		baseImage.Format = MagickFormat.Png;

		baseImage.Composite(templateImage, CompositeOperator.Over);

		int textPoint = 0;
		foreach (var textArea in imageTemplate.TextPositions)
		{
			baseImage.WriteText(texts[textPoint], textArea, MagickColors.White, Encoding.Unicode);
			textPoint++;
		}

		return baseImage.ToByteArray();
	}
}