using System;
using System.Drawing;
using System.IO;
using System.Windows.Media.Imaging;
using CamBooth.App.Core.Logging;
using QRCoder;

namespace CamBooth.App.Features.PhotoPrismUpload;

/// <summary>
/// Service für die Generierung von QR-Codes als BitmapImage (PhotoPrism)
/// </summary>
public class QRCodeGenerationService
{
	private readonly Logger _logger;

	public QRCodeGenerationService(Logger logger)
	{
		_logger = logger;
	}

	/// <summary>
	/// Generiert einen QR-Code basierend auf einem URL-String
	/// </summary>
	/// <param name="qrData">Die Daten für den QR-Code (z.B. URL)</param>
	/// <param name="pixelsPerModule">Größe in Pixeln pro QR-Code-Modul</param>
	/// <returns>BitmapImage des QR-Codes oder null bei Fehler</returns>
	public BitmapImage? GenerateQRCode(string qrData, int pixelsPerModule = 20)
	{
		try
		{
			_logger.Debug($"Generiere PhotoPrism QR-Code für: {qrData}");

			using (QRCodeGenerator qrGenerator = new QRCodeGenerator())
			{
				QRCodeData qrCodeData = qrGenerator.CreateQrCode(qrData, QRCodeGenerator.ECCLevel.Q);
				using (QRCode qrCode = new QRCode(qrCodeData))
				{
					Bitmap qrCodeImage = qrCode.GetGraphic(pixelsPerModule, System.Drawing.Color.Black, System.Drawing.Color.White, true);
					
					// Konvertiere Bitmap zu BitmapImage
					BitmapImage bitmapImage = ConvertBitmapToBitmapImage(qrCodeImage);
					
					_logger.Debug("✅ PhotoPrism QR-Code erfolgreich generiert");
					return bitmapImage;
				}
			}
		}
		catch (Exception ex)
		{
			_logger.Error($"Fehler beim Generieren des PhotoPrism QR-Codes: {ex.Message}");
			return null;
		}
	}

	/// <summary>
	/// Konvertiert ein System.Drawing.Bitmap zu einem WPF BitmapImage
	/// </summary>
	private BitmapImage ConvertBitmapToBitmapImage(Bitmap bitmap)
	{
		using (var stream = new MemoryStream())
		{
			bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
			stream.Seek(0, SeekOrigin.Begin);

			var bitmapImage = new BitmapImage();
			bitmapImage.BeginInit();
			bitmapImage.StreamSource = stream;
			bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
			bitmapImage.EndInit();
			bitmapImage.Freeze();

			return bitmapImage;
		}
	}
}
