@page "/Products/Index"

@using Gremlin_BlazorServer.Data.EntityClasses;
@using Gremlin_BlazorServer.Services;
@using System.Globalization;
@using System.Diagnostics;

@inject ProductService productService

<h1>Products</h1>

@if (products is null)
{
    <p><em>Loading... !</em></p>
}
else
{
    <p>Es wurden @products.Count Products gefunden.</p> 
    @if (products != null)
    {
        <DataGrid 
            TItem="Product" 
            Data="@products" 
            @bind-SelectedRow="@selectedProduct"
            @*ReadData="@OnReadData"*@
            PageSize="10"
            ShowPager
            Bordered
            Hoverable
            Striped
            Responsive>
        <DataGridCommandColumn />
        <DataGridColumn Field="@nameof(Product.ProductId)" Caption="#"/>
        <DataGridColumn Field="@nameof(Product.ProductNumber)" Caption="ProductNumber" Editable />
        <DataGridColumn Field="@nameof(Product.OptionNumber)" Caption="OptionNumber" Editable />
        <DataGridColumn Field="@nameof(Product.ListPrice)" Caption="ListPrice"  DisplayFormat="{0:C}" DisplayFormatProvider=cultureInfo Editable />
        <DataGridColumn Field="@nameof(Product.ProductStatus)" Caption="ProductStatus" Editable />
        @*<DataGridColumn Field="@nameof(Product.IntroductionDate)" Caption="IntroductionDate" Editable />                *@
        </DataGrid>

        <p>Product @selectedProduct.ProductNumber selected.</p>                
    }
}

@code {
    public string searchProduct = "";
    CultureInfo cultureInfo = new("de-DE");

    Product selectedProduct = new();
    List<Product> products = new();

    protected override async Task OnParametersSetAsync()
    {
        products = await Task.Run(() => productService.GetAllProductsAsync());
        selectedProduct = products.FirstOrDefault()!;
    }

    //private async Task OnReadData(DataGridReadDataEventArgs<Product> eventArgs)
    //{
    //    if (!eventArgs.CancellationToken.IsCancellationRequested)
    //    {
    //        List<Product> response = new();

    //        if (eventArgs.ReadDataMode is DataGridReadDataMode.Virtualize)
    //            response = (await productService.GetAllProductsAsync()).Skip(eventArgs.VirtualizeOffset).Take(eventArgs.VirtualizeCount).ToList();
    //        else if (eventArgs.ReadDataMode is DataGridReadDataMode.Paging)
    //            response = (await productService.GetAllProductsAsync()).Skip((eventArgs.Page - 1) * eventArgs.PageSize).Take(eventArgs.PageSize).ToList();
    //        else
    //            throw new Exception("Unhandled ReadDataMode");

    //        if (!eventArgs.CancellationToken.IsCancellationRequested)
    //        {
    //            totalProducts = (await productService.GetAllProductsAsync()).Count;
    //            products = new List<Product>(response); // an actual data for the current page
    //        }
    //    }
    //}
}