using Elwig.Helpers;
using Elwig.Models.Entities;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace Elwig.Windows {

    public partial class OriginHierarchyWindow : ContextWindow {

        private bool isUpdating = false;

        public OriginHierarchyWindow() {
            InitializeComponent();
            ActivateKgButton.IsEnabled = false;
            DeactivateKgButton.IsEnabled = false;
        }

        protected override async Task OnRenewContext(AppDbContext ctx) {
            var origins = (await ctx.WineOrigins
                    .Include("Gems.AtGem.Kgs.WbKg.Gl")
                    .AsSplitQuery()
                    .ToListAsync())
                    .OrderByDescending(o => o.SortKey)
                    .ThenBy(o => o.HkId);
            ControlUtils.RenewItemsSource(WineOrigins, origins, WineOrigins_SelectionChanged);
            if (WineOrigins.SelectedItem == null) {
                var hkid = await ctx.WbKgs
                    .GroupBy(k => k.AtKg.Gem.WbGem!.HkId)
                    .Where(g => g.Count() > 0)
                    .OrderByDescending(g => g.Count())
                    .Select(g => g.Key)
                    .FirstOrDefaultAsync();
                ControlUtils.SelectItemWithPk(WineOrigins, hkid);
            }
            var gls = await ctx.WbGls
                .OrderBy(g => g.GlNr)
                .Include("Kgs.Rds")
                .AsSplitQuery()
                .ToListAsync();
            ControlUtils.RenewItemsSource(WbGls, gls, WbGls_SelectionChanged, ControlUtils.RenewSourceDefault.First);
            UpdateWbGems();
            UpdateWbKgs();
            UpdateWbGlKgs();
            UpdateWbRds();
        }

        private void UpdateWbGems() {
            WbGemsHeader.Content = "Gemeinden" + (WineOrigins.SelectedItem is WineOrigin o ? $" ({o.Name})" : "");
            var origin = (WineOrigins.SelectedItem as WineOrigin);
            var gems = origin?.Gems.Select(g => g.AtGem).OrderBy(g => g.Name).ToList();
            ControlUtils.RenewItemsSource(WbGems, gems, WbGems_SelectionChanged);
            UpdateWbKgs();
        }

        private void UpdateWbKgs() {
            WbKgsHeader.Content = "Verfügbare KG";
            IEnumerable<AT_Kg>? kgs = null;
            if (WbGems.SelectedItem is AT_Gem g) {
                WbKgsHeader.Content += $" ({g.Name})";
                kgs = g.Kgs;
            } else if (WineOrigins.SelectedItem is WineOrigin o) {
                WbKgsHeader.Content += $" ({o.Name})";
                kgs = o.Gems.SelectMany(g => g.AtGem.Kgs);
            } else {
                kgs = null;
            }
            var kgList = kgs?.OrderBy(k => k.WbKg?.Gl == null).ThenBy(k => k.WbKg?.GlNr).ThenBy(k => k.Name).ToList();
            ControlUtils.RenewItemsSource(WbKgs, kgList, WbKgs_SelectionChanged);
        }

        private void UpdateWbGlKgs() {
            WbGlKgsHeader.Content = "Aktive KG";
            if (WbGls.SelectedItem is WbGl g) {
                WbGlKgsHeader.Content += $" ({g.Name})";
                var kgs = g.Kgs.Select(k => k.AtKg).OrderBy(k => k.Name).ToList();
                ControlUtils.RenewItemsSource(WbGlKgs, kgs, WbGlKgs_SelectionChanged);
            } else {
                WbGlKgs.ItemsSource = null;
            }
            UpdateButtons();
        }

        private async Task UpdateStatusBar() {
            StatusKgName.Text = "Katastralgemeinde: ";
            StatusWbRds.Text = "Riede: ";
            StatusDefaultKgs.Text = "Stammgemeinde: ";
            StatusAreaCommitments.Text = "Flächenbindungen: ";
            StatusDeliveries.Text = "Lieferungen: ";
            if (WbGlKgs.SelectedItem is AT_Kg k && k.WbKg != null) {
                using var ctx = new AppDbContext();
                StatusKgName.Text += $"{k.Name} ({k.KgNr:00000})";
                var reeds = await ctx.WbRde.Where(r => r.KgNr == k.KgNr).CountAsync();
                StatusWbRds.Text += $"{reeds:N0}";
                var activeMembers = await ctx.Members.Where(m => m.IsActive && m.DefaultKgNr == k.KgNr).CountAsync();
                var allMembers = await ctx.Members.Where(m => m.DefaultKgNr == k.KgNr).CountAsync();
                StatusDefaultKgs.Text += $"{activeMembers:N0} ({allMembers:N0})";
                var year = Utils.CurrentNextSeason;
                var activeAreaComs = await Utils.ActiveAreaCommitments(ctx.AreaCommitments.Where(c => c.KgNr == k.KgNr), year).CountAsync();
                var allAreaComs = await ctx.AreaCommitments.Where(c => c.KgNr == k.KgNr).CountAsync();
                StatusAreaCommitments.Text += $"{activeAreaComs:N0} ({allAreaComs:N0})";
                var deliveryParts = await ctx.DeliveryParts.Where(p => p.KgNr == k.KgNr).CountAsync();
                var deliveries = await ctx.Deliveries.Where(d => d.Parts.Any(p => p.KgNr == k.KgNr)).CountAsync();
                StatusDeliveries.Text += $"{deliveries:N0} ({deliveryParts:N0})";
            } else {
                StatusKgName.Text += "-";
                StatusWbRds.Text += "-";
                StatusDefaultKgs.Text += "-";
                StatusAreaCommitments.Text += "-";
                StatusDeliveries.Text += "-";
            }
        }

        private void UpdateWbRds() {
            WbRdsHeader.Content = "Riede";
            if (WbGlKgs.SelectedItem is AT_Kg k) {
                WbRdsHeader.Content += $" ({k.Name})";
                var rds = k.WbKg?.Rds.OrderBy(r => r.Name).ToList();
                ControlUtils.RenewItemsSource(WbRds, rds);
            } else {
                WbRds.ItemsSource = null;
            }
            UpdateButtons();
        }

        private void WineOrigins_SelectionChanged(object sender, SelectionChangedEventArgs evt) {
            UpdateWbGems();
        }

        private void WbGls_SelectionChanged(object? sender, SelectionChangedEventArgs? e) {
            UpdateWbGlKgs();
        }

        private void WbGems_SelectionChanged(object? sender, SelectionChangedEventArgs? e) {
            UpdateWbKgs();
        }

        private async void WbGlKgs_SelectionChanged(object sender, SelectionChangedEventArgs e) {
            UpdateWbRds();
            if (!isUpdating && WbGlKgs.SelectedItem is AT_Kg k) {
                isUpdating = true;
                ControlUtils.SelectItemWithPk(WineOrigins, k.Gem.WbGem?.HkId);
                ControlUtils.SelectItemWithPk(WbGems, k.Gkz);
                ControlUtils.SelectItemWithPk(WbKgs, k.KgNr);
                isUpdating = false;
            }
            await UpdateStatusBar();
        }

        private void WbKgs_SelectionChanged(object sender, SelectionChangedEventArgs e) {
            UpdateButtons();
            if (!isUpdating && WbKgs.SelectedItem is AT_Kg k && k.WbKg != null && ((WbGls.SelectedItem as WbGl)?.GlNr == k.WbKg?.GlNr || WbGls.SelectedItem == null)) {
                isUpdating = true;
                ControlUtils.SelectItemWithPk(WbGls, k.WbKg?.GlNr);
                ControlUtils.SelectItemWithPk(WbGlKgs, k.KgNr);
                isUpdating = false;
            }
        }

        private void UpdateButtons() {
            if (WbKgs.SelectedItem is AT_Kg v) {
                ActivateKgButton.IsEnabled = v.WbKg?.GlNr != (WbGls.SelectedItem as WbGl)?.GlNr;
                ActivateKgButton.ToolTip = $"KG {v.Name} Großlage {(WbGls.SelectedItem as WbGl)?.Name} zuweisen";
            } else {
                ActivateKgButton.IsEnabled = false;
                ActivateKgButton.ToolTip = $"Verfügbare Katastralgemeinde Großlage {(WbGls.SelectedItem as WbGl)?.Name} zuweisen";
            }

            if (WbGlKgs.SelectedItem is AT_Kg a) {
                DeactivateKgButton.IsEnabled = true;
                DeactivateKgButton.ToolTip = $"KG {a.Name} deaktivieren";
            } else {
                DeactivateKgButton.IsEnabled = false;
                DeactivateKgButton.ToolTip = "Aktive Katastralgemeinde deaktivieren";
            }
        }

        private async void ActivateKgButton_Click(object sender, RoutedEventArgs e) {
            if (WbKgs.SelectedItem is not AT_Kg k || WbGls.SelectedItem is not WbGl g) return;
            try {
                var kg = new WbKg { KgNr = k.KgNr, GlNr = g.GlNr };
                using (var ctx = new AppDbContext()) {
                    if (k.WbKg != null) {
                        ctx.Update(kg);
                    } else {
                        ctx.Add(kg);
                    }
                    await ctx.SaveChangesAsync();
                }
                App.HintContextChange();
                ControlUtils.SelectItemWithPk(WbGlKgs, k.KgNr);
            } catch (Exception exc) {
                var str = "Der Eintrag konnte nicht in der Datenbank aktualisiert werden!\n\n" + exc.Message;
                if (exc.InnerException != null) str += "\n\n" + exc.InnerException.Message;
                MessageBox.Show(str, "Katastralgemeinde aktivieren", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async void DeactivateKgButton_Click(object sender, RoutedEventArgs e) {
            if (WbGlKgs.SelectedItem is not AT_Kg k || k.WbKg == null) return;
            var r = MessageBox.Show(
                $"Sollen alle Riede und Stammgemeinden-Einträge von der KG {k.Name} wirklich unwiderruflich gelöscht werden?",
                "Katastralgemeinde deaktivieren", MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No);
            if (r != MessageBoxResult.Yes) return;
            try {
                using (var ctx = new AppDbContext()) {
                    ctx.Remove(k.WbKg);
                    await ctx.SaveChangesAsync();
                }
                App.HintContextChange();
                ControlUtils.SelectItemWithPk(WbKgs, k.KgNr);
            } catch (Exception exc) {
                await HintContextChange();
                var str = "Der Eintrag konnte nicht aus der Datenbank gelöscht werden!\n\n" + exc.Message;
                if (exc.InnerException != null) str += "\n\n" + exc.InnerException.Message;
                MessageBox.Show(str, "Katastralgemeinde deaktivieren", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        public void FocusKgNr(int kgnr) {
            using var ctx = new AppDbContext();
            var kg = ctx.Katastralgemeinden.Find(kgnr);
            ControlUtils.SelectItemWithPk(WbGls, kg?.WbKg?.GlNr);
            ControlUtils.SelectItemWithPk(WbGlKgs, kg?.KgNr);
            WbGlKgs.Focus();
            WbGlKgs.ScrollIntoView(kg?.WbKg?.Gl);
        }
    }
}
