using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using Microsoft.Win32;
using EDPlayerJournal.Entries;
using EliteBGS.Util;
using EDPlayerJournal.BGS;

namespace EliteBGS;

/// <summary>
/// Interaction logic for LoadEntriesWindow.xaml
/// </summary>
public partial class LoadEntriesWindow : Window {
    public delegate void EntriesLoadedDelegate(List<Entry> entries);

    public event EntriesLoadedDelegate EntriesLoaded;

    Config config = new Config();

    public LoadEntriesWindow() {
        InitializeComponent();
    }

    private void Load_Click(object sender, RoutedEventArgs e) {
        string lines = Lines.Text.Trim();
        if (lines.Length <= 0) {
            return;
        }

        try {
            List<Entry> entries = new List<Entry>();

            foreach (string line in lines.Split('\n')) {
                if (string.IsNullOrEmpty(line)) {
                    continue;
                }
                Entry entry = Entry.Parse(line);
                entries.Add(entry);
            }

            if (entries.Count > 0) {
                EntriesLoaded?.Invoke(entries);
            }
        } catch (Exception exception) {
            MessageBox.Show(string.Format("There was an error while parsing the JSON: {0}",
                exception.ToString()));
        }
    }

    private void Clear_Click(object sender, RoutedEventArgs e) {
        Lines.Clear();
    }

    private void LoadFile_Click(object sender, RoutedEventArgs e) {
        OpenFileDialog dialog = new OpenFileDialog();

        dialog.DefaultExt = ".log";
        dialog.Filter = "Log files (*.log)|*.log|All files (*.*)|*";

        var location = AppConfig.DefaultJournalLocation;
        if (Directory.Exists(location)) {
            dialog.InitialDirectory = location;
        }

        bool result = dialog.ShowDialog(this) ?? false;
        if (!result) {
            return;
        }

        try {
            using (FileStream stream = File.OpenRead(dialog.FileName)) {
                using (StreamReader reader = new StreamReader(stream)) {
                    Lines.Text = reader.ReadToEnd();
                }
            }
        } catch (Exception) {
        }
    }

    private void DeleteUnimportant_Click(object sender, RoutedEventArgs e) {
        string lines = Lines.Text.Trim();
        if (lines.Length <= 0) {
            return;
        }

        TransactionParser parser = new();

        try {
            List<Entry> entries = new List<Entry>();

            foreach (string line in lines.Split('\n')) {
                if (string.IsNullOrEmpty(line)) {
                    continue;
                }
                Entry entry = Entry.Parse(line);
                if (parser.IsRelevant(entry)) {
                    entries.Add(entry);
                }
            }

            if (entries.Count <= 0) {
                return;
            }

            string[] text = entries
                .ConvertAll(x => x.JSON.ToString(Newtonsoft.Json.Formatting.None))
                .ToArray()
                ;
            Lines.Text = string.Join("\n", text).Trim();
        } catch (Exception exception) {
            MessageBox.Show(string.Format("There was an error while parsing the JSON: {0}",
                exception.ToString()));
        }
    }
}
