using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Resources;

namespace Noctalk.UI.Windowing;

public sealed class Noctalk_window_icon_handler
{
    private readonly System.Windows.Window window;
    private readonly Noctalk_window_icon_app app;
    private readonly Dictionary<Noctalk_window_icon_state, ImageSource> iconsByState = [];
    private Noctalk_window_icon_state? currentState;

    public Noctalk_window_icon_handler(System.Windows.Window The_window, Noctalk_window_icon_app The_app)
    {
        window = The_window;
        app = The_app;
    }

    public Noctalk_window_icon_state? Current_state => currentState;

    public void Window_icon__set(Noctalk_window_icon_state The_state)
    {
        if (currentState == The_state)
        {
            return;
        }

        currentState = The_state;
        ImageSource icon = Window_icon__get(The_state);
        if (window.Dispatcher.CheckAccess())
        {
            window.Icon = icon;
            return;
        }

        window.Dispatcher.BeginInvoke(() => window.Icon = icon);
    }

    private ImageSource Window_icon__get(Noctalk_window_icon_state The_state)
    {
        if (iconsByState.TryGetValue(The_state, out ImageSource? icon))
        {
            return icon;
        }

        string resourcePath = Window_icon__resource_path__get(The_state);
        StreamResourceInfo? resourceInfo = Application.GetResourceStream(new Uri(resourcePath, UriKind.Relative));
        if (resourceInfo is null)
        {
            throw new FileNotFoundException($"Embedded icon resource was not found: {resourcePath}");
        }

        using Stream stream = resourceInfo.Stream;
        BitmapFrame bitmapFrame = BitmapFrame.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad);
        bitmapFrame.Freeze();
        iconsByState[The_state] = bitmapFrame;
        return bitmapFrame;
    }

    private string Window_icon__resource_path__get(Noctalk_window_icon_state The_state)
    {
        string appPrefix = app == Noctalk_window_icon_app.Server ? "server" : "client";
        string stateName = The_state switch
        {
            Noctalk_window_icon_state.Online => "online",
            Noctalk_window_icon_state.Offline => "offline",
            _ => "initializing"
        };

        return $"Icons/{appPrefix}_{stateName}.ico";
    }
}
