using System;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;

namespace MaddoShared;

/// <summary>
/// Dynamically resolves the concrete IImageCreator implementation at call time
/// based on current PicSettings.ImageCreatorProvider.
/// </summary>
public class ImageCreatorMapper : IImageCreator
{
    private readonly IServiceProvider _sp;
    private readonly PicSettings _settings;
    private readonly ILogger<ImageCreatorMapper> _logger;

    public ImageCreatorMapper(IServiceProvider sp, PicSettings settings, ILogger<ImageCreatorMapper> logger)
    {
        _sp = sp ?? throw new ArgumentNullException(nameof(sp));
        _settings = settings ?? throw new ArgumentNullException(nameof(settings));
        _logger = logger;
    }

    public Task CreateImageAsync(ImageState imgState, System.Drawing.Image logo)
    {
        var provider = (_settings.ImageCreatorProvider ?? "Sharp").Trim();
        _logger?.LogDebug("Resolving IImageCreator for provider '{Provider}'", provider);

        return provider.Equals("ALTERNATE", StringComparison.OrdinalIgnoreCase)
            ? ResolveAndCall<ImageCreatorAlternate>(imgState, logo)
            : ResolveAndCall<ImageCreatorSharp>(imgState, logo);
    }

    private Task ResolveAndCall<T>(ImageState imgState, System.Drawing.Image logo) where T : IImageCreator
    {
        // Resolve the concrete implementation and forward the call
        var impl = (IImageCreator)_sp.GetService(typeof(T));
        if (impl is null)
        {
            _logger?.LogWarning("Requested image creator {Type} is not registered. Falling back to ImageCreatorSharp.", typeof(T).Name);
            impl = (IImageCreator)_sp.GetService(typeof(ImageCreatorSharp));
        }

        if (impl is null)
            throw new InvalidOperationException("No IImageCreator implementation is registered.");

        return impl.CreateImageAsync(imgState, logo);
    }
}
