@page "/Guilds"
@using System.Net.Http.Headers
@using System.Reflection
@using Spacebar.Models.AdminApi
@using Spacebar.AdminApi.TestClient.Services
@using ArcaneLibs.Blazor.Components
@using ArcaneLibs.Extensions
@inject Config Config
@inject ILocalStorageService LocalStorage

<PageTitle>Guilds</PageTitle>

<details>
    <summary>Displayed columns</summary>
    @foreach (var column in DisplayedColumns) {
        var value = column.Value;
        <span>
        <InputCheckbox @bind-Value:get="@(value)" @bind-Value:set="@(b => {
                                                                       DisplayedColumns[column.Key] = b;
                                                                       StateHasChanged();
                                                                   })"/>
            @column.Key.Name
    </span>
        <br/>
    }
</details>

<p>Got @GuildList.Count guilds.</p>
<table class="table table-bordered">
    @{
        var columns = DisplayedColumns.Where(kvp => kvp.Value).Select(kvp => kvp.Key).ToList();
    }
    <thead>
        <tr>
            @foreach (var column in columns) {
                <th>@column.Name</th>
            }
            <th>Actions</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var user in GuildList.Where(x => !x.Unavailable).OrderByDescending(x=>x.MessageCount)) {
            <tr>
                @foreach (var column in columns) {
                    <td>@column.GetValue(user)</td>
                }
                <td>
                    <LinkButton href="@($"/Users/Delete/{user.Id}")" Color="#ff0000">Delete</LinkButton>
                </td>
            </tr>
        }
    </tbody>
</table>

@code {

    private Dictionary<PropertyInfo, bool> DisplayedColumns { get; set; } = typeof(GuildModel).GetProperties()
        .ToDictionary(p => p, p => p.Name == "Name" || p.Name == "Id" || p.Name == "MessageCount");

    private List<GuildModel> GuildList { get; set; } = new();

    protected override async Task OnInitializedAsync() {
        var hc = new StreamingHttpClient();
        hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Config.AccessToken);

        // var request = new HttpRequestMessage(HttpMethod.Get, Config.AdminUrl + "/_spacebar/admin/users/");
        
        var response = hc.GetAsyncEnumerableFromJsonAsync<GuildModel>(Config.AdminUrl + "/_spacebar/admin/guilds/");
        // if (!response.IsSuccessStatusCode) throw new Exception(await response.Content.ReadAsStringAsync());
        // var content = response.Content.ReadFromJsonAsAsyncEnumerable<GuildModel>();
        await foreach (var user in response) {
            // Console.WriteLine(user.ToJson(indent: false, ignoreNull: true));
            GuildList.Add(user!);
            if(GuildList.Count % 1000 == 0)
                StateHasChanged();
        }
        StateHasChanged();
    }

}