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.Chapters;

public partial class Chapters
{
    public List<Chapter> chapters;

    private int totalChapter;

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

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

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

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

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

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

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


    private async void OnDelete(int id)
    {
        var parameters = new ModalParameters();
        parameters.Add(nameof(Chapter.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/chapter/" + 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("chapters", true);
    }

    private async Task OnReadData(DataGridReadDataEventArgs<Chapter> 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<Chapter[]>(API.API_URL + "all/chapters/" + API.TOKEN + "/" + page);

        if (!e.CancellationToken.IsCancellationRequested)
        {
            chapters = new List<Chapter>(response); // an actual data for the current page
            totalChapter = response[0].total_chapters;
        }
    }
}
