using Blazored.LocalStorage;
using Blazor.Services;
using Blazored.Modal.Services;
using Blazor.ViewClasses;
using System.Text;
using Microsoft.JSInterop;
using Microsoft.AspNetCore.Components;
using Blazorise.DataGrid;
using ChoETL;
using Microsoft.AspNetCore.Components.Forms;
using Blazor.Modals;
using Blazored.Modal;
using Blazor.Pages.Admins;
using Blazor.Pages.Chapters;

namespace Blazor.Pages.Players;

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

    private int totalPlayer;

    [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(Player.Id), id);

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

        if (result.IsCanceled)
        {
            return;
        }

        await DataService.Delete(id);

        // Reload the page
        NavigationManager.NavigateTo("Players", true);
    }


    //protected override async Task OnAfterRenderAsync(bool firstRender)
    //{
    //    // Do not treat this action if is not the first render
    //    if (!firstRender)
    //    {
    //        return;
    //    }
    //}

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

        var response = Http.GetFromJsonAsync<Player[]>($"https://trusting-panini.87-106-126-109.plesk.page/api/players").Result;

        if (!e.CancellationToken.IsCancellationRequested)
        {
            players = new List<Player>(response); // an actual data for the current page
            totalPlayer = players.Count;
            var currentData = await LocalStorage.GetItemAsync<Player[]>("data");
            if (currentData == null || currentData.Length != players.Count)
            {
                var originalData = Http.GetFromJsonAsync<Player[]>($"https://trusting-panini.87-106-126-109.plesk.page/api/players").Result;
                await LocalStorage.SetItemAsync("data", originalData);
            }
        }
    }
}

