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

namespace WK5_Blazor.Components
{
    public partial class LieferantenZugänge : IAsyncDisposable
    {
        [Parameter] public int LieferantenId { get; set; }
        public ZugangFilter Filter { get; set; } = new ZugangFilter();

        private CancellationTokenSource _cts = new CancellationTokenSource();
        private List<Zugang> _results = new List<Zugang>();
        private Zugang? _selectedZugang;

        private int _totalItems;
        private bool _isLoading;
        protected override async Task OnParametersSetAsync()
        {
            Filter.LieferantenId = LieferantenId;
            Filter.Option = ZugangFilterOption.Alle;
            await LadeAsync();
        }

        private async Task LadeAsync(int seite = 1)
        {
            _isLoading = true;
            _cts.Cancel();
            _cts = new CancellationTokenSource();
            _results.Clear();
            Filter.Seite = seite;
            var token = _cts.Token;

            try
            {
                await foreach (var item in lagerService.GetZugängeAsync(Filter, token))
                {
                    _results.Add(item);
                    StateHasChanged();
                }

                _totalItems = await lagerService.GetAnzahlZugängeAsnyc(Filter, token);
            }
            catch (OperationCanceledException){}

            _isLoading = false;
        }
        public ValueTask DisposeAsync()
        {
            _cts?.Cancel();
            _cts?.Dispose();
            _results.Clear();

            return ValueTask.CompletedTask;
        }
    }
}
