using Elwig.Helpers;
using Elwig.Helpers.Billing;
using Elwig.Helpers.Export;
using Elwig.Models.Dtos;
using Elwig.Models.Entities;
using Microsoft.Win32;
using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;

namespace Elwig.Windows {
    public partial class SeasonFinishWindow : ContextWindow {
        public SeasonFinishWindow() {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs evt) {
            SeasonInput.Value = Utils.CurrentLastSeason;
        }

        protected override Task OnRenewContext(AppDbContext ctx) {
            SeasonInput_ValueChanged(null, null);
            return Task.CompletedTask;
        }

        private async void SeasonInput_ValueChanged(object? sender, RoutedEventArgs? evt) {
            using var ctx = new AppDbContext();
            var s0 = await ctx.Seasons.FindAsync(SeasonInput.Value);
            var s1 = await ctx.Seasons.FindAsync(SeasonInput.Value + 1);
            var valid = (s0 != null);
            var last = (s1 == null);
            CalculateBucketsButton.IsEnabled = valid && last;
            DeliveryConfirmationButton.IsEnabled = valid;
            OverUnderDeliveryButton.IsEnabled = valid;
            AutoBusinessSharesButton.IsEnabled = valid;
            PaymentButton.IsEnabled = valid;
            AllowAttrIntoLowerInput.IsEnabled = valid && last;
            AvoidUnderDeliveriesInput.IsEnabled = valid && last;
            HonorGebundenInput.IsEnabled = valid && last;
            AllowAttrIntoLowerInput.IsChecked = s0?.Billing_AllowAttrsIntoLower;
            AvoidUnderDeliveriesInput.IsChecked = s0?.Billing_AvoidUnderDeliveries;
            HonorGebundenInput.IsChecked = s0?.Billing_HonorGebunden;
        }

        private async void CalculateBucketsButton_Click(object sender, RoutedEventArgs evt) {
            if (SeasonInput.Value is not int year)
                return;
            CalculateBucketsButton.IsEnabled = false;
            Mouse.OverrideCursor = Cursors.AppStarting;

            try {
                using var ctx = new AppDbContext();
                if (await ctx.Seasons.FindAsync(year) is not Season s)
                    return;

                s.Billing_AllowAttrsIntoLower = AllowAttrIntoLowerInput.IsChecked ?? false;
                s.Billing_AvoidUnderDeliveries = AvoidUnderDeliveriesInput.IsChecked ?? false;
                s.Billing_HonorGebunden = HonorGebundenInput.IsChecked ?? false;
                ctx.Update(s);
                await ctx.SaveChangesAsync();
            } catch { }

            var b = new Billing(year);
            await b.FinishSeason();
            await b.CalculateBuckets();
            await App.HintContextChange();

            Mouse.OverrideCursor = null;
            CalculateBucketsButton.IsEnabled = true;
        }

        private void DeliveryConfirmationButton_Click(object sender, RoutedEventArgs evt) {
            if (SeasonInput.Value is not int year)
                return;
            var w = App.FocusMailWindow(year);
            w.AddDeliveryConfirmation();
        }

        private async void OverUnderDeliveryButton_Click(object sender, RoutedEventArgs evt) {
            if (SeasonInput.Value is not int year)
                return;
            var d = new SaveFileDialog() {
                FileName = $"Über-Unterlieferungen-{year}.ods",
                DefaultExt = "ods",
                Filter = "OpenDocument Format Spreadsheet (*.ods)|*.ods",
                Title = $"Über-/Unterlieferungen {year} speichern unter - Elwig"
            };
            if (d.ShowDialog() == false)
                return;

            Mouse.OverrideCursor = Cursors.AppStarting;
            try {
                using var ctx = new AppDbContext();
                var tbl1 = await OverUnderDeliveryData.ForSeason(ctx.OverUnderDeliveryRows, year);
                var tbl2 = await AreaComUnderDeliveryData.ForSeason(ctx.AreaComUnderDeliveryRows, year);
                var tbl3 = await MemberDeliveryPerVariantData.ForSeason(ctx.MemberDeliveryPerVariantRows, year);
                using var ods = new OdsFile(d.FileName);
                await ods.AddTable(tbl1);
                await ods.AddTable(tbl2);
                await ods.AddTable(tbl3);
            } catch (Exception exc) {
                MessageBox.Show(exc.Message, "Fehler", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            Mouse.OverrideCursor = null;
        }

        private async void AutoBusinessSharesButton_Click(object sender, RoutedEventArgs evt) {
            if (SeasonInput.Value is not int year)
                return;
            if (false && App.Client.IsMatzen) {
                AutoBusinessSharesButton.IsEnabled = false;
                Mouse.OverrideCursor = Cursors.AppStarting;

                var b = new Billing(year);
                await b.AutoAdjustBusinessShare();

                Mouse.OverrideCursor = null;
                AutoBusinessSharesButton.IsEnabled = true;
            } else {
                MessageBox.Show(
                    "Es ist kein automatisches Nachzeichnen der Geschäftsanteile\n" +
                    "für diese Genossenschaft eingestellt!\n" +
                    "Bitte wenden Sie sich an die Programmierer!", "Fehler",
                    MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void PaymentButton_Click(object sender, RoutedEventArgs evt) {
            if (SeasonInput.Value is not int year)
                return;
            App.FocusPaymentVariants(year);
        }
    }
}
