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

namespace WK5_Blazor.Components.Lieferanten
{
    public partial class LieferantenSuche : IDisposable
    {
        [Parameter] public EventCallback<Lieferant> OnLieferantSelected { get; set; }
        [Parameter] public LieferantenFilter Filter { get; set; } = new LieferantenFilter();

        private List<Lieferant> suchergebnisse = new List<Lieferant>();

        private CancellationTokenSource _ctsSuche = new CancellationTokenSource();

        private bool parametersSet = false;

        protected override async Task OnParametersSetAsync()
        {
            if (!parametersSet)
            {
                await Suchen();
                parametersSet = true;
            }
        }

        private async Task Suchen()
        {
            _ctsSuche.Cancel();
            _ctsSuche = new CancellationTokenSource();
            suchergebnisse.Clear();

            await foreach (var lieferant in lieferantenService.GetLieferantenAsync(Filter, _ctsSuche.Token))
            {
                suchergebnisse.Add(lieferant);
                StateHasChanged();
            }
        }

        private void OnTableRowKeyUp(KeyboardEventArgs e, Lieferant lieferant)
        {
            if (e.Code == "Enter" || e.Key == "Enter")
            {
                OnLieferantSelected.InvokeAsync(lieferant);
            }
        }

        public void Dispose()
        {
            _ctsSuche.Cancel();
            _ctsSuche.Dispose();
        }
    }
}
