using Elwig.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;

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

        record struct Row (DateTime DateTime, string Type, int MgNr, string Name, string Addresses, string Subject, string Attachments);

        private List<Row> Data = [];

        public MailLogWindow() {
            InitializeComponent();
            WindowState = WindowState.Maximized;
            ControlUtils.InitializeDelayTimer(FilterInput, FilterInput_TextChanged);
            FilterInput.TextChanged -= FilterInput_TextChanged;
        }

        private async void Window_Loaded(object sender, RoutedEventArgs evt) {
            await Load();
        }

        private async void TimeSpanInput_SelectionChanged(object sender, RoutedEventArgs evt) {
            if (!IsLoaded) return;
            await Load();
        }

        private async Task Load() {
            DateTime? fromDate = DateTime.Now;
            if (TimeSpanInput.SelectedIndex == 0) {
                fromDate = fromDate.Value.AddDays(-7);
            } else if (TimeSpanInput.SelectedIndex == 1) {
                fromDate = fromDate.Value.AddMonths(-6);
            } else {
                fromDate = null;
            }
            var mails = await Utils.GetSentMails(fromDate: fromDate == null ? null : DateOnly.FromDateTime(fromDate.Value));
            Data = mails.Reverse().Select(m => new Row(
                m.DateTime,
                m.Type == "email" ? "E-Mail" : m.Type == "postal" ? "Post" : "?",
                m.MgNr,
                m.Name,
                string.Join("\n", m.Addresses),
                m.Subject,
                string.Join("\n", m.Attachments)
            )).ToList();
            MailList.ItemsSource = Data;
            ApplyFilters();
        }

        private void FilterInput_TextChanged(object sender, RoutedEventArgs evt) {
            ApplyFilters();
        }

        private void TypeInput_SelectionChanged(object sender, RoutedEventArgs evt) {
            ApplyFilters();
        }

        private void ApplyFilters() {
            if (!IsLoaded) return;
            var filters = FilterInput.Text.Split(' ');
            IEnumerable<Row> data = Data;
            switch (TypeInput.SelectedIndex) {
                case 1: data = data.Where(d => d.Type == "Post"); break;
                case 2: data = data.Where(d => d.Type == "E-Mail"); break;
            }
            foreach (var filter in filters) {
                if (int.TryParse(filter, out var mgnr)) {
                    data = data.Where(d => d.MgNr == mgnr);
                } else {
                    var f = filter.ToLower();
                    data = data.Where(d => d.Name.Contains(f, StringComparison.CurrentCultureIgnoreCase) ||
                                           d.Addresses.Contains(f, StringComparison.CurrentCultureIgnoreCase) ||
                                           d.Subject.Contains(f, StringComparison.CurrentCultureIgnoreCase) ||
                                           d.Attachments.Contains(f, StringComparison.CurrentCultureIgnoreCase));
                }
            }
            if (IsLoaded)
                MailList.ItemsSource = data.ToList();
        }

        private async void MailList_SelectionChanged(object sender, RoutedEventArgs evt) {
            if (MailList.SelectedItem is not Row item) return;
            if (item.Type == "E-Mail") {
                MailData.Text = await Utils.FindSentMailBody(item.DateTime);
            } else {
                MailData.Text = "";
            }
        }
    }
}
