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;
using WK5.Core.Models.Statistik;

namespace WK5_Blazor.Pages.Statistik.Verkauf
{
    public partial class TopArtikelNachLieferant : IAsyncDisposable
    {
        public TopArtikelNachLieferantFilter Filter { get; set; } = new TopArtikelNachLieferantFilter();

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

        private async Task LadeAsync()
        {
            _cts.Cancel();
            _cts.Dispose();
            _cts = new CancellationTokenSource();
            var token = _cts.Token;
            _results.Clear();
            _isLoading = true;
            using FbController2 fbController = new FbController2();
            await foreach (var item in statistikService.GetTopArtikelNachLieferantAsync(Filter, fbController, token))
            {
                _results.Add(item);
                StateHasChanged();
            }

            _isLoading = false;
        }
        
        private async Task LieferantIdChangedAsync(int lieferantId)
        {
            Filter.LieferantId = lieferantId;
            Lieferant? lieferant = await Lieferant.GetLieferantAsync(lieferantId);
            Filter.Suchbegriff = lieferant?.LIEF_A_NAME1 ?? string.Empty;
        }
        private Task SelectLieferantAsync(Lieferant lieferant)
        {
            Filter.LieferantId = lieferant.LIEF_N_NR;
            Filter.Suchbegriff = lieferant.LIEF_A_NAME1;
            _showLieferantenSucheModal = false;
            return Task.CompletedTask;
        }
        public ValueTask DisposeAsync()
        {
            _cts.Cancel();
            _cts.Dispose();
            return ValueTask.CompletedTask;
        }
    }
}
