using Microsoft.AspNetCore.Components;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using WK5.Core.Basis.Filter;
using WK5.Core.Models;

namespace WK5_Blazor.Components
{
    public partial class Pakete
    {
        [Parameter] public PaketFilter Filter { get; set; } = new PaketFilter();
        [Parameter] public bool AllowChangeTyp { get; set; } = false;
        [Parameter] public bool AllowChangeNummer { get; set; } = false;
        [Parameter] public bool ShowWert { get; set; } = false;

        private List<W4Paket> Ergebnisse { get; set; } = new List<W4Paket>();
        private bool _sperre { get; set; } = false;
        private CancellationTokenSource cancellationToken = new CancellationTokenSource();

        protected override async Task OnParametersSetAsync()
        {
            await Suchen();
        }

        private async Task Suchen()
        {
            _sperre = true;
            cancellationToken.Cancel();
            Ergebnisse.Clear();

            cancellationToken = new CancellationTokenSource();
            await Task.Run(async () =>
            {
                await foreach (var paket in paketService.GetPaketeAsync(Filter, cancellationToken.Token))
                {
                    if (paket != null)
                    {
                        Ergebnisse.Add(paket);
                        await InvokeAsync(StateHasChanged);
                    }
                }

            });
            _sperre = false;
        }
    }
}
