using System.Reflection;
using System.Runtime.CompilerServices;
using System.Xml;
using FModel.Extensions.Themes;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit.Highlighting.Xshd;

namespace FModel.Extensions;

public sealed record HighlightColor
(
    string Foreground,
    bool Bold = false,
    bool Italic = false
);

public static class AvalonExtensions
{
    private static readonly IHighlightingDefinition _jsonHighlighter = LoadHighlighter("Json.xshd");
    private static readonly IHighlightingDefinition _iniHighlighter = LoadHighlighter("Ini.xshd");
    private static readonly IHighlightingDefinition _xmlHighlighter = LoadHighlighter("Xml.xshd");
    private static readonly IHighlightingDefinition _cppHighlighter = LoadHighlighter("Cpp.xshd");
    private static readonly IHighlightingDefinition _changelogHighlighter = LoadHighlighter("Changelog.xshd");
    private static readonly IHighlightingDefinition _verseHighlighter = LoadHighlighter("Verse.xshd");
    private static readonly IHighlightingDefinition _luaHighlighter = LoadHighlighter("Lua.xshd");

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    private static IHighlightingDefinition LoadHighlighter(string resourceName)
    {
        var executingAssembly = Assembly.GetExecutingAssembly();
        using var stream = executingAssembly.GetManifestResourceStream($"{executingAssembly.GetName().Name}.Resources.{resourceName}");
        using var reader = new XmlTextReader(stream);
        return HighlightingLoader.Load(reader, HighlightingManager.Instance);
    }

    [MethodImpl(MethodImplOptions.AggressiveInlining)]
    public static IHighlightingDefinition HighlighterSelector(string ext)
    {
        switch (ext)
        {
            case "lua":
            case "luac":
                return _luaHighlighter;
            case "ini":
            case "csv":
                return _iniHighlighter;
            case "xml":
            case "tps":
                return _xmlHighlighter;
            case "h":
            case "cpp":
                return _cppHighlighter;
            case "changelog":
                return _changelogHighlighter;
            case "verse":
                return _verseHighlighter;
            case "bat":
            case "txt":
            case "pem":
            case "js":
            case "po":
                return null;
            default:
                _jsonHighlighter.ApplyJsonTheme(Settings.UserSettings.Default.JsonHighlightTheme);
                return _jsonHighlighter;
        }
    }
}
