using System;
using System.IO;
using System.Windows;
using InABox.Core;
using Microsoft.Web.WebView2.Core;

namespace InABox.Wpf.DynamicGrid.Controls;

public partial class MonacoEditor : Window
{
    
    private static string MonacoFolder = Path.Combine(
        AppDomain.CurrentDomain.BaseDirectory,
        @"MonacoEditor");

    const string defaultText = @"function helloWorld() {\n\tconsole.log(""Hello world!"");\n}"; 
    public string Text { get; private set; } = defaultText;
    
    public MonacoEditor(string script)
    {
        Text = script;
        InitializeComponent();
        webView21.NavigationCompleted += WebView21_NavigationCompleted;
        webView21.WebMessageReceived += WebView21_WebMessageReceived;

        webView21.Source = new Uri(Path.Combine(MonacoFolder, "index.html"));
    }
    
    private void WebView21_NavigationCompleted(object? sender, CoreWebView2NavigationCompletedEventArgs e)
    {
        webView21.ExecuteScriptAsync(@$"buildEditor(`{Text}`);");
    }

    private void WebView21_WebMessageReceived(object? sender, CoreWebView2WebMessageReceivedEventArgs e)
    {
        Text = e.TryGetWebMessageAsString();
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        webView21.ExecuteScriptAsync(@$"doAction(`cursorUndo`);");
    }

    private void WebView21_OnSizeChanged(object sender, SizeChangedEventArgs e)
    {
        //webView21.InvalidateVisual();
        //webView21.Source = new Uri(Path.Combine(MonacoFolder, "index.html"));
    }

    private void MonacoEditor_OnSizeChanged(object sender, SizeChangedEventArgs e)
    {
        //webView21.ExecuteScriptAsync(@$"buildEditor(`{Text}`);");
    }
}