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

namespace WK5_Blazor.Components.Suchen
{
    public partial class KundenSuche : IAsyncDisposable
    {
        [Parameter] public EventCallback<Kunde> OnKundeSelected { get; set; }
        [Parameter] public EventCallback<KundenÜbersicht> OnKundeClicked { get; set; }
        [Parameter] public KundenÜbersichtFilter Filter { get; set; } = new KundenÜbersichtFilter();

        private List<KundenÜbersicht> _suchergebnisse = new List<KundenÜbersicht>();
        private CancellationTokenSource _cts = new CancellationTokenSource();
        private Guid _id;

        public KundenSuche()
        {
            _id = Guid.NewGuid();
        }

        protected override async Task OnAfterRenderAsync(bool firstRender)
        {
            if (!firstRender)
            {
                await jsRuntime.FocusByIdAsync($"kunden-suche-{_id}");
            }
        }

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


        private async Task Suchen()
        {
            _cts.Cancel();
            _cts.Dispose();
            _cts = new CancellationTokenSource();
            var token = _cts.Token;
            _suchergebnisse = await kundenService.GetKundenÜbersichtAsync(Filter, token).ToListAsync();
        }

        private async Task KundeSelected(KundenÜbersicht kunde)
        {
            await kundenService.UpdateWichtigkeitAsync(kunde.KUNU_A_NR);
            Kunde? k = await Kunde.GetKundeAsync(kunde.KUNU_A_NR);
            await OnKundeSelected.InvokeAsync(k);
        }

        public ValueTask DisposeAsync()
        {
            _cts?.Cancel();
            _cts?.Dispose();

            return ValueTask.CompletedTask;
        }
    }
}
