using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using WK5.Core;
using WK5.Core.Basis.Filter.Statistik;
using WK5.Core.Models.Statistik;

namespace WK5_Blazor.Pages.Statistik
{
    public partial class AbgelehnteAngebote : IAsyncDisposable
    {
        public AbgelehnteAngeboteFilter Filter { get; set; } = new AbgelehnteAngeboteFilter();
        private CancellationTokenSource _cts = new CancellationTokenSource();
        private bool _lädt;
        private List<AbgelehnteAngeboteResult> _results = new();
        protected override async Task OnInitializedAsync()
        {
            await LadeAsync();
        }
        private async Task LadeAsync()
        {
            _cts.Cancel();
            _cts.Dispose();
            _cts = new CancellationTokenSource();
            var token = _cts.Token;
            _results.Clear();
            _lädt = true;
            using FbController2 fbController = new FbController2();
            try
            {
                await foreach (var item in statistikService.GetAbgelehnteAngeboteAsync(Filter, fbController, token))
                {
                    _results.Add(item);
                    StateHasChanged();
                }
            }
            catch (OperationCanceledException){}

            _lädt = false;
        }

        private Task WarengruppeChangedAsync(string warengruppe)
        {
            Filter.Warengruppe = warengruppe;
            Filter.Unterwarengruppe = string.Empty;
            Filter.Artikelnummer = string.Empty;
            return Task.CompletedTask;
        }

        private Task ArtikelnummerChangedAsync(string artikelnummer)
        {
            Filter.Artikelnummer = artikelnummer;
            Filter.Warengruppe = string.Empty;
            Filter.Unterwarengruppe = string.Empty;
            return Task.CompletedTask;
        }

        public ValueTask DisposeAsync()
        {
            _cts.Cancel();
            _cts.Dispose();
            return ValueTask.CompletedTask;
        }
    }
}
