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.Umsatzstatistik;

namespace WK5_Blazor.Pages.Statistik.Umsatzstatistik
{
    public partial class LieferantenUmsatz : IAsyncDisposable
    {
        public LieferantenUmsatzFilter Filter { get; set; } = new LieferantenUmsatzFilter();

        private CancellationTokenSource _cts = new CancellationTokenSource();
        private List<LieferantenUmsatzResult> _results = new List<LieferantenUmsatzResult>();
        private bool _isLoading;

        protected override async Task OnInitializedAsync()
        {
            await LadeAsync();
        }

        private async Task LadeAsync()
        {
            _results.Clear();
            _cts.Cancel();
            _cts.Dispose();
            _cts = new CancellationTokenSource();

            var token = _cts.Token;
            _isLoading = true;
            using FbController2 fbController = new FbController2();
            try
            {
                await foreach (var item in statistikService.GetLieferantenUmsatzAsync(Filter, fbController, token))
                {
                    _results.Add(item);
                    StateHasChanged();
                }
            }
            catch (OperationCanceledException){}
            finally
            {
                _isLoading = false;
            }
            
        }

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