using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Xml;
using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.AvalonEdit.Highlighting.Xshd;
using SparkClient.ViewModel.Configuration;

namespace SparkClient.Views.Configuration;

public partial class AlgorithmConfigPage 
{

    public AlgorithmConfigPage()
    {
        InitializeComponent();
        DataContext = new AlgorithmConfigVM();

        using (Stream stream = typeof(MainWindow).Assembly.GetManifestResourceStream(@"SparkClient.Resource.Other.Json-Mode-Default.xshd"))
        using (XmlReader reader = new XmlTextReader(stream))
        {
            IHighlightingDefinition highlightingDefinition = HighlightingLoader.Load(reader, HighlightingManager.Instance);
            HighlightingManager.Instance.RegisterHighlighting("JSON Highlighting", new string[] { ".json" }, highlightingDefinition);
            TextEditor.SyntaxHighlighting = highlightingDefinition;
        }

        if (DataContext is AlgorithmConfigVM vm)
        {
            TextEditor.Text = vm.AlgorithmConfigJson;
            vm.PropertyChanged += (s, e) =>
            {
                if (e.PropertyName == nameof(vm.AlgorithmConfigJson))
                {
                    if (TextEditor.Text != vm.AlgorithmConfigJson)
                    {
                        TextEditor.Text = vm.AlgorithmConfigJson;
                    } 
                }
            };
        }
    }

    private void TextEditor_OnTextChanged(object? sender, EventArgs e)
    {
        if(DataContext is AlgorithmConfigVM vm)
            vm.AlgorithmConfigJson = TextEditor.Text;
        
    }
}