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

namespace WK5_Blazor.Pages.Stammdaten.Artikeldaten
{
    public class SeriennummernSucheModel
    {
        public string? Suche { get; set; } = String.Empty;
    }

    public partial class SeriennummernSuche
    {
        [Parameter] public string Suche { get; set; } = string.Empty;

        [Parameter] public bool ComponentView { get; set; }
        private SeriennummernSucheModel Model { get; set; } = new SeriennummernSucheModel();

        public bool IsLoading { get; set; } = false;
        public List<ArtikelSNVerlauf> Ergebnis { get; set; } = new List<ArtikelSNVerlauf>();
        public CancellationTokenSource CancellationToken { get; set; } = new CancellationTokenSource();

        protected override Task OnParametersSetAsync()
        {
            Model.Suche = Suche;
            return Task.CompletedTask;
        }
        private async Task Suchen()
        {
            IsLoading = true;
            StateHasChanged();
            await Task.Delay(1);
            Ergebnis.Clear();

            Model.Suche = Model.Suche?.Trim();

            if (String.IsNullOrWhiteSpace(Model.Suche))
            {
                await jsRuntime.ShowToast(ToastType.error, "Die Suche darf nicht leer sein!");
                IsLoading = false;
                return;
            }

            CancellationToken.Cancel();
            CancellationToken = new CancellationTokenSource();

            await foreach (ArtikelSNVerlauf result in artikelService.FindSN(Model.Suche, CancellationToken.Token))
            {
                Ergebnis.Add(result);
                StateHasChanged();
            }

            IsLoading = false;
        }

        private bool isSortedAscending;
        private string? activeSortColumn;
        private string sortIcon = "arrow-down";

        private void SortTable(string columnName)
        {
            if (columnName != activeSortColumn)
            {
                Ergebnis = Ergebnis.OrderBy(x => x.GetType().GetProperty(columnName)!.GetValue(x, null)).ToList();
                isSortedAscending = true;
                activeSortColumn = columnName;
            }
            else
            {
                if (isSortedAscending)
                {
                    Ergebnis = Ergebnis.OrderByDescending(x => x.GetType()!.GetProperty(columnName)!.GetValue(x, null)).ToList();
                }
                else
                {
                    Ergebnis = Ergebnis.OrderBy(x => x.GetType()!.GetProperty(columnName)!.GetValue(x, null)).ToList();
                }
                isSortedAscending = !isSortedAscending;
            }

            sortIcon = isSortedAscending ? "fas fa-arrow-up" : "fas fa-arrow-down";
        }
    }
}
