using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Nodify.Calculator
{
    /// <summary>
    /// Interaction logic for FlowRunner.xaml
    /// </summary>
    public partial class FlowRunner : Window
    {
        private readonly Executor _executor;

        public FlowRunner(Executor executor)
        {
            InitializeComponent();
            _executor = executor;
        }

        private void WriteLog(string message, logType logtype)
        {
            // IMPORTANT: UI updates must happen on the main UI thread.
            // Dispatcher.Invoke ensures that, even if the event is fired from a background thread.
            Dispatcher.Invoke(() =>
            {
                // Choose a color based on the log type
                Brush color = Brushes.White; // Default for Information
                switch (logtype)
                {
                    case logType.Warning:
                        color = Brushes.Yellow;
                        break;
                    case logType.Error:
                        color = Brushes.Red;
                        break;
                }

                // Create a text run with the specified color
                var run = new Run($"{DateTime.Now:HH:mm:ss} [{logtype}]: {message}\n")
                {
                    Foreground = color
                };

                // Add the text to a new paragraph and add the paragraph to the RichTextBox
                var paragraph = new Paragraph();
                paragraph.Inlines.Add(run);
                LogRichTextBox.Document.Blocks.Add(paragraph);

                // Auto-scroll to the bottom
                LogRichTextBox.ScrollToEnd();
            });
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Task.Run(() => {
                _executor.OnLogMe += WriteLog;
                _executor.Execute();
            });   
        }
    }
}
