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

namespace Elwig.Windows {
    public partial class BaseDataWindow {

        private bool _seasonChanged = false;
        private bool _seasonUpdate = false;

        private async Task SeasonsInitEditing(AppDbContext ctx) {
            ControlUtils.RenewItemsSource(SeasonList, await ctx.Seasons.OrderByDescending(s => s.Year).ToListAsync());
            SeasonList_SelectionChanged(null, null);
        }

        private async Task SeasonsFinishEditing(AppDbContext ctx) {
            ControlUtils.RenewItemsSource(SeasonList, await ctx.Seasons.OrderByDescending(s => s.Year).Include(s => s.Modifiers).ToListAsync());
            _seasonChanged = false;
        }

        private async Task SeasonsSave(AppDbContext ctx) {
            if (!_seasonChanged || SeasonList.SelectedItem is not Season s)
                return;
            ctx.Update(s);
            await ctx.SaveChangesAsync();
        }

        private void SeasonList_SelectionChanged(object? sender, SelectionChangedEventArgs? evt) {
            _seasonUpdate = true;
            if (SeasonList.SelectedItem is Season s) {
                SeasonModifierList.ItemsSource = s.Modifiers.OrderBy(m => m.Ordering).ToList();
                SeasonMaxKgPerHaInput.Text = s.MaxKgPerHa.ToString();
                SeasonVatNormalInput.Text = (s.VatNormal * 100).ToString();
                SeasonVatFlatrateInput.Text = (s.VatFlatrate * 100).ToString();
                SeasonStartInput.Text = $"{s.StartDate:dd.MM.yyyy}";
                SeasonEndInput.Text = $"{s.EndDate:dd.MM.yyyy}";
                SeasonMinKgPerBsInput.Text = s.MinKgPerBusinessShare.ToString();
                SeasonMaxKgPerBsInput.Text = s.MaxKgPerBusinessShare.ToString();
                SeasonPenaltyPerKgInput.Text = s.PenaltyPerKg?.ToString() ?? "";
                SeasonPenaltyInput.Text = s.PenaltyAmount?.ToString() ?? "";
                SeasonPenaltyNoneInput.Text = s.PenaltyNone?.ToString() ?? "";
                SeasonBsValueInput.Text = s.BusinessShareValue?.ToString() ?? "";

                var sym = s.Currency.Symbol ?? "";
                SeasonModifierAbsInput.Unit = $"{sym}/kg";
                SeasonPenaltyPerKgInput.Unit = $"{sym}/kg";
                SeasonPenaltyInput.Unit = sym;
                SeasonPenaltyNoneInput.Unit = sym;
                SeasonBsValueInput.Unit = $"{sym}/GA";
                AreaCommitmentTypePenaltyPerKgInput.Unit = $"{sym}/kg";
                AreaCommitmentTypePenaltyInput.Unit = sym;
                AreaCommitmentTypePenaltyNoneInput.Unit = sym;
            } else {
                SeasonModifierList.ItemsSource = null;
                SeasonMaxKgPerHaInput.Text = "";
                SeasonVatNormalInput.Text = "";
                SeasonVatFlatrateInput.Text = "";
                SeasonStartInput.Text = "";
                SeasonEndInput.Text = "";
                SeasonMinKgPerBsInput.Text = "";
                SeasonMaxKgPerBsInput.Text = "";
                SeasonPenaltyPerKgInput.Text = "";
                SeasonPenaltyInput.Text = "";
                SeasonPenaltyNoneInput.Text = "";
                SeasonBsValueInput.Text = "";
            }
            _seasonUpdate = false;
        }

        private void Season_Changed(object? sender, RoutedEventArgs? evt) {
            if (_seasonUpdate || (!IsEditing && !IsCreating) || SeasonList.SelectedItem is not Season s) return;
            _seasonChanged = true;

            if (SeasonMaxKgPerHaInput.Text.Length > 0)
                s.MaxKgPerHa = int.Parse(SeasonMaxKgPerHaInput.Text);
            if (SeasonVatNormalInput.Text.Length > 0)
                s.VatNormal = double.Parse(SeasonVatNormalInput.Text) / 100;
            if (SeasonVatFlatrateInput.Text.Length > 0)
                s.VatFlatrate = double.Parse(SeasonVatFlatrateInput.Text) / 100;
            if (SeasonMinKgPerBsInput.Text.Length > 0)
                s.MinKgPerBusinessShare = int.Parse(SeasonMinKgPerBsInput.Text);
            if (SeasonMaxKgPerBsInput.Text.Length > 0)
                s.MaxKgPerBusinessShare = int.Parse(SeasonMaxKgPerBsInput.Text);
            s.PenaltyPerKg = (SeasonPenaltyPerKgInput.Text.Length > 0) ? decimal.Parse(SeasonPenaltyPerKgInput.Text) : null;
            s.PenaltyAmount = (SeasonPenaltyInput.Text.Length > 0) ? decimal.Parse(SeasonPenaltyInput.Text) : null;
            s.PenaltyNone = (SeasonPenaltyNoneInput.Text.Length > 0) ? decimal.Parse(SeasonPenaltyNoneInput.Text) : null;
            s.BusinessShareValue = (SeasonBsValueInput.Text.Length > 0) ? decimal.Parse(SeasonBsValueInput.Text) : null;

            UpdateButtons();
        }

        private void SeasonMinMaxKgInput_TextChanged(object sender, TextChangedEventArgs evt) {
            InputTextChanged((TextBox)sender, Validator.CheckInteger((TextBox)sender, true, 5));
            Season_Changed(sender, evt);
        }

        private void SeasonVatInput_TextChanged(object sender, TextChangedEventArgs evt) {
            InputTextChanged((TextBox)sender, Validator.CheckDecimal((TextBox)sender, true, 2, 1));
            Season_Changed(sender, evt);
        }

        private void SeasonPenaltyPerKgInput_TextChanged(object sender, TextChangedEventArgs evt) {
            if (SeasonList.SelectedItem is not Season s) return;
            InputTextChanged((TextBox)sender, Validator.CheckDecimal((TextBox)sender, false, 2, s.Precision));
            Season_Changed(sender, evt);
        }

        private void SeasonPenaltyInput_TextChanged(object sender, TextChangedEventArgs evt) {
            InputTextChanged((TextBox)sender, Validator.CheckDecimal((TextBox)sender, false, 4, 2));
            Season_Changed(sender, evt);
        }
    }
}
