@using SharpRss.Models
@using SharpRss.Services
@using WebSharpRSS.Models
@using Serilog

@inject SyndicationService _service;

<MudPaper Height="100%" Width="80vh">
    @if (Category != null)
    {
        <div style="justify-self: start;" class="d-flex align-center my-2">
            <MudIcon Icon="@Category.Icon" Style="@($"color:{Category.HexColor}")" Class="mx-2"/>
            <MudText>@Category.Name</MudText>
        </div>
        <MudDivider/>
        @if (_isLoading)
        {
            <div class="d-flex justify-center">
                <div>
                    <MudProgressCircular Class="d-block" Color="Color.Primary" Indeterminate="true"/>
                    <MudText Class="d-block">Loading...</MudText>
                </div>
            </div>
        }
        else
        {
            <div style="display: flex; height: 80vh; overflow-y: scroll">
                <SyndicationListItem Items="@items"/>
            </div>
        }
    }
    else
    {
        <MudText>Could not load data!</MudText>
    }
</MudPaper>

@code {
    [Parameter]
    public CategoryModel? Category { get; set; }

    bool _isLoading = true;
    HashSet<SyndicationItemData> items = new HashSet<SyndicationItemData>();
    
    async Task LoadDataAsync()
    {
        if (Category == null)
        {
            Log.Warning("Category is null!");
            return;
        }
        _isLoading = true;
        var syndicationIds = Category.Syndications.Select(x => x.EncodedUrl);
        var syndicationItems = await _service.GetSyndicationItemsFromSyndicationsAsync(syndicationIds.ToArray());
        items = syndicationItems.Select(x => SyndicationItemData.FromModel(x)).OrderBy(x => x.PublishingDate).Reverse().ToHashSet();
        _isLoading = false;
    }
    protected override void OnInitialized()
    {
        Task.Run(async () => await LoadDataAsync()).ContinueWith(async t => await InvokeAsync(StateHasChanged));
    }
}