using Microsoft.Graphics.Canvas;
using Microsoft.Graphics.Canvas.UI.Xaml;

namespace ReactorMaintenance.Win2D;

public sealed class EditorImageRegistry
{
    public async Task LoadAsync(CanvasControl sender)
    {
        m_Images.Clear();
        await LoadFolderAsync(sender, "Images", "Props");
        await LoadFolderAsync(sender, "Images", "Pipes");
        await LoadFolderAsync(sender, "Images", "Badges");
        await LoadFolderAsync(sender, "Images", "Elements");
        AddAlias("tool-floor", "floor");
        AddAlias("tool-wall", "wall");
        AddAlias("tool-heat", "heat");
        AddAlias("tool-robot", "robot");
        AddAlias("robot", "robot");
        AddAlias("prop-reactor", "reactor");
        AddAlias("prop-consumer", "generator");
        AddAlias("prop-flow", "generator");
        AddAlias("carrier-fuel-source", "generator");
        AddAlias("carrier-coolant-source", "cooling-pump");
        AddAlias("carrier-electricity-source", "generator");
        AddAlias("prop-junction", "pressure-regulator");
        AddAlias("prop-door", "wall");
        AddAlias("prop-eye-terminal", "diagnostic-terminal");
        AddAlias("prop-remedy", "repair");
        AddAlias("leak-fuel", "leak");
        AddAlias("leak-coolant", "leak");
        AddAlias("leak-electricity", "leak");
        AddAlias("hazard-heat", "heat");
        AddAlias("hazard-fuel", "fire");
        AddAlias("hazard-coolant", "leak");
        AddAlias("hazard-electricity", "heat");
    }

    public CanvasBitmap? Get(string key)
    {
        return m_Images.GetValueOrDefault(key);
    }

    private async Task LoadFolderAsync(CanvasControl sender, params string[] pathParts)
    {
        var folder = Path.Combine([AppContext.BaseDirectory, .. pathParts]);
        if (!Directory.Exists(folder))
            return;

        foreach (var path in Directory.EnumerateFiles(folder, "*.png"))
        {
            var key = Path.GetFileNameWithoutExtension(path);
            m_Images[key] = await CanvasBitmap.LoadAsync(sender, path);
        }
    }

    private void AddAlias(string alias, string key)
    {
        if (!m_Images.ContainsKey(alias) && m_Images.TryGetValue(key, out var image))
            m_Images[alias] = image;
    }

    private readonly Dictionary<string, CanvasBitmap> m_Images = new(StringComparer.OrdinalIgnoreCase);
}