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

<PageTitle>Uploaded media by user</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>

<InputSelect @bind-Value="@SelectedUserId">
    <option value="">All users</option>
    @if (UserList is { Count: > 0 }) {
        @foreach (var user in UserList.OrderByDescending(u => u.Id).Where(x => !x.Deleted)) {
            <option value="@user.Id">@user.Username</option>
        }
    }
</InputSelect>


<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 UserMedia) {
            <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(FileMetadataModel).GetProperties()
        .ToDictionary(p => p, p => p.Name == "Username" || p.Name == "Id" || p.Name == "MessageCount");

    private List<UserModel> UserList { get; set; } = new();
    private List<FileMetadataModel> UserMedia { get; set; } = new();

    [SupplyParameterFromQuery(Name = "UserId")]
    public string? SelectedUserId {
        get;
        set {
            field = value;
            if (string.IsNullOrWhiteSpace(field))
                UserMedia.Clear();
            else _ = GetMediaForUser(value!);
        }
    }

    protected override async Task OnInitializedAsync() {
        using var hc = new HttpClient();
        hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Config.AccessToken);
        var response = await hc.GetAsync(Config.AdminUrl + "/_spacebar/admin/users/");
        if (!response.IsSuccessStatusCode) throw new Exception(await response.Content.ReadAsStringAsync());
        var content = response.Content.ReadFromJsonAsAsyncEnumerable<UserModel>();
        await foreach (var user in content) {
            UserList.Add(user!);
            StateHasChanged();
        }
    }

    private async Task GetMediaForUser(string userId) {
        using var hc = new HttpClient();
        hc.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", Config.AccessToken);
        var response = await hc.GetAsync(Config.AdminUrl + $"/_spacebar/admin/media/user/{userId}/attachments");
        if (!response.IsSuccessStatusCode) throw new Exception(await response.Content.ReadAsStringAsync());
        var content = response.Content.ReadFromJsonAsAsyncEnumerable<FileMetadataModel>();
        await foreach (var media in content) {
            UserMedia.Add(media!);
            StateHasChanged();
        }
    }

}