using Elwig.Helpers;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace Elwig.Windows {
    public partial class LogWindow : Window {

        public LogWindow() {
            InitializeComponent();
            WindowState = WindowState.Maximized;
        }

        private async void Window_Loaded(object sender, RoutedEventArgs evt) {
            Mouse.OverrideCursor = Cursors.Wait;
            await Task.Run(async () => {
                var list = Utils.GetLogEntries()
                  .Select(e => new {
                      Event = e,
                      Lines = e.Message.Split('\n').ToArray(),
                  })
                  .Select(e => new {
                      e.Event,
                      Exception = e.Lines.FirstOrDefault(l => l.StartsWith("Exception Info: "))?[16..].Trim().Split(':', 2),
                      Location = e.Lines.FirstOrDefault(l => l.StartsWith("   at Elwig."))?[5..].Trim(),
                  })
                  .Select(e => new {
                      e.Event,
                      e.Exception,
                      ExceptionName = e.Exception?[0].Trim(),
                      ExceptionMessage = e.Exception?.Length >= 2 ? e.Exception?[1].Trim() : null,
                      e.Location,
                  })
                  .OrderByDescending(e => e.Event.TimeGenerated)
                  .ToList();
                await App.MainDispatcher.BeginInvoke(() => {
                    EventList.ItemsSource = list;
                    EventList.SelectedIndex = 0;
                });
            });
            Mouse.OverrideCursor = null;
        }

        private void EventList_SelectionChanged(object sender, RoutedEventArgs evt) {
            var item = EventList.SelectedItem;
            var t = item.GetType();
            var p = t.GetProperty("Event")!;
            EventData.Text = ((EventLogEntry)p.GetValue(item)!).Message;
        }
    }
}
