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

namespace WK5_Blazor.Pages.Verkauf.RMAS
{
    public partial class RmaÜbersicht : IHasPageFilter
    {
        [Parameter] public int Seite { get => _seite; set => _seite = value < 1 ? 1 : value; }
        public int TotalItems { get; set; }
        public RmaFilter Filter { get; set; } = new RmaFilter();


        private bool _lädt;
        private int _seite;
        private readonly List<Rma> _rmas = new List<Rma>();
        private CancellationTokenSource _cts = new CancellationTokenSource();
        private bool _showHilfeModal;

        private string GetRowClass(Rma rma)
        {
            if(rma.Erledigt)
            {
                return "table-success";
            }

            if(rma.LetzteÄnderung.AddDays(7).Date < DateTime.Today.Date)
            {
                return "table-danger";
            }

            return string.Empty;
        }

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

        private async Task ResetFilterAsync()
        {
            Filter = new RmaFilter();
            await LadeRmasAsync();
        }

        private async Task LadeRmasAsync()
        {
            _cts.Cancel();
            _cts.Dispose();
            _cts = new CancellationTokenSource();
            _rmas.Clear();

            Filter.Seite = Seite;

            var token = _cts.Token;
            //await LocalStorage.SetAsync(LocalStorageFilterKey, Filter);
            using FbController2 fbController = new FbController2();
            try
            {
                TotalItems = await rmaService.GetAnzahlRmasAsync(Filter, fbController, token);
                await foreach (var rma in rmaService.GetRmasAsync(Filter, fbController, token))
                {
                    _rmas.Add(rma);
                    StateHasChanged();
                }
            }
            catch (ObjectDisposedException)
            {
                // Tritt auf, wenn die Seite gewechselt wird, aber noch Daten geladen werden
            }
            catch (Exception)
            {
                Filter = new RmaFilter();
                //await LocalStorage.SetAsync(LocalStorageFilterKey, Filter);
                throw;
            }
        }
    }
}
