using OpenArchival.Blazor.ArtifactGroupingDisplay;
using System.Collections.Generic;
using System.Collections.Specialized;

namespace OpenArchival.Blazor;

public class FileDisplayComponentFactory
{
    private Dictionary<string, Type> _extensionToComponents { get; set; } = [];
    
    public FileDisplayComponentFactory()
    {
        // Supported image file types taken from https://developer.mozilla.org/en-US/docs/Web/Media/Guides/Formats/Image_types
        RegisterComponent<FileDisplayImage>(".apng");
        RegisterComponent<FileDisplayImage>(".png");
        RegisterComponent<FileDisplayImage>(".avif");
        RegisterComponent<FileDisplayImage>(".gif");
        RegisterComponent<FileDisplayImage>(".jpg");
        RegisterComponent<FileDisplayImage>(".jpeg");
        RegisterComponent<FileDisplayImage>(".jfif");
        RegisterComponent<FileDisplayImage>(".pjpeg");
        RegisterComponent<FileDisplayImage>(".pjg");
        RegisterComponent<FileDisplayImage>(".png");
        RegisterComponent<FileDisplayImage>(".svg");
        RegisterComponent<FileDisplayImage>(".webp");
    }    

    private string GetExtensionKey(string pathOrExtension)
    {
        return Path.GetExtension(pathOrExtension).ToUpperInvariant();
    }    

    public bool RegisterComponent<ComponentType>(string filenameOrExtension) where ComponentType : IFileDisplayComponent 
    {
        string extensionString = GetExtensionKey(filenameOrExtension); 

        _extensionToComponents.Add(extensionString, typeof(ComponentType));
        return true;
    }

    public Type? GetDisplayComponentType(string filenameOrExtension) {
        var result = _extensionToComponents.TryGetValue(GetExtensionKey(filenameOrExtension), out var component);

        return (result) ? component : null; 
    }
}
