using Blazored.LocalStorage;
using Blazor.Services;
using Blazored.Modal.Services;
using Blazor.ViewClasses;
using Microsoft.JSInterop;
using Microsoft.AspNetCore.Components;
using Blazorise.DataGrid;
using Blazor.Modals;
using Blazored.Modal;
using Microsoft.Extensions.Localization;

namespace Blazor.Pages.Players;

public partial class Players
{
    public List<Player> players;

    private int totalPlayer;

    [Inject]
    public IStringLocalizer<Players> Localizer { get; set; }

    [Inject]
    public required NavigationManager NavigationManager { get; set; }

    [CascadingParameter]
    public required IModalService Modal { get; set; }

    [Inject]
    public required IDataService DataService { get; set; }
    [Inject]
    public required IWebHostEnvironment WebHostEnvironment { get; set; }

    [Inject]
    public required HttpClient Http { get; set; }

    [Inject]
    public required ILocalStorageService LocalStorage { get; set; }

    [Inject]
    public required IJSRuntime IJSRuntime { get; set; }

    private async void OnDelete(int id)
    {
        var parameters = new ModalParameters();
        parameters.Add(nameof(Player.Id), id);

        var modal = Modal.Show<DeleteConfirmation>("Delete Confirmation", parameters);
        var result = await modal.Result;

        if (result.Cancelled)
        {
            return;
        }

        string apiUri = API.API_URL+"delete/player/" + id + "/" + API.TOKEN;

        using (var httpClient = new HttpClient())
        {
            var response = await httpClient.DeleteAsync(apiUri);

            if (response.IsSuccessStatusCode)
            {
                var responseBody = await response.Content.ReadAsStringAsync();
            }
            else
            {
                var errorResponse = await response.Content.ReadAsStringAsync();
            }
        }
        NavigationManager.NavigateTo("Players", true);
    }

    private async Task OnReadData(DataGridReadDataEventArgs<Player> e)
    {
        if (e.CancellationToken.IsCancellationRequested)
        {
            return;
        }

        // Calculez l'index de départ pour la pagination
        int page = ((e.Page - 1) * e.PageSize) / 10 + 1;

        // Envoyez une requête à l'API pour récupérer les questions de la page actuelle
        var response = await Http.GetFromJsonAsync<Player[]>(API.API_URL + "all/players/" + API.TOKEN + "/" + page);

        if (!e.CancellationToken.IsCancellationRequested)
        {
            players = new List<Player>(response); // an actual data for the current page
            totalPlayer = response[0].total_players; ;
        }
    }
}

