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

namespace WK5_Blazor.Components
{
    public partial class BelegSuche : IAsyncDisposable
    {
        [Parameter] public EventCallback<Beleg> OnBelegSelected { get; set; }
        [Parameter] public EventCallback<Beleg> OnBelegClick { get; set; }
        [Parameter] public BelegFilter Filter { get; set; } = new BelegFilter();
        [Parameter] public bool ShowPositionen { get; set; } = true;

        private readonly List<Beleg> suchergebnisse = new List<Beleg>();

        private CancellationTokenSource _cts = new CancellationTokenSource();

        private Beleg? _selectedBeleg;

        private bool _selectedBelegIsLoading;
        private async Task Suchen()
        {
            suchergebnisse.Clear();
            _cts.Cancel();
            _cts.Dispose();
            _cts = new CancellationTokenSource();

            var token = _cts.Token;

            using FbController2 fbController = new FbController2();
            try
            {
                await foreach (var artikel in belegService.SucheBelegeAsync(Filter, fbController, token))
                {
                    suchergebnisse.Add(artikel);
                    StateHasChanged();
                }
            }
            catch (OperationCanceledException){}
            
        }

        private string GetRowClass(Beleg beleg)
        {
            if(beleg == _selectedBeleg)
            {
                return "table-secondary";
            }

            return string.Empty;
        }
        protected override async Task OnInitializedAsync()
        {
            await Suchen();
        }

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