@page "/list"
@using WebSharpRSS.Models
@using SharpRss.Services

@inject IDialogService _dialogService;
@inject SyndicationService _syndicationService;

<title>@_title</title>
<div>
    @if (_isLoading)
        {
            <div class="d-flex justify-center">
                <div>
                    <MudProgressCircular Class="d-block" Color="Color.Primary" Indeterminate="true" Size="Size.Large"/>
                    <MudText Class="d-block">Loading...</MudText>
                </div>
            </div>
        }
        else
        {
            <SyndicationListItem Items="items"/>
        }
</div>

@code {
    [Parameter]
    [SupplyParameterFromQuery(Name = "fid")]
    public string? Fid
    { 
        get => _fid;
        set
        {
            _fid = value;
            Task.Run(async () => await LoadItems());
        }
    }
    private string? _fid;
    [Parameter]
    [SupplyParameterFromQuery(Name = "cid")]
    public string? Cid
    {
        get => _cid;
        set
        {
            _cid = value;
            Task.Run(async () => await LoadItems());
        }
    }

    private string _title { get; set; } = "List syndication - SharpRss";
    private string? _cid;
    HashSet<SyndicationItemData> items = new HashSet<SyndicationItemData>();
    bool _isLoading = true;
    private async Task LoadItems()
    {
        _isLoading = true;
        if (Fid != null)
        {
            var fItems = await _syndicationService.GetSyndicationItemsAsync(Fid);
            items = fItems.Select(x => SyndicationItemData.FromModel(x)).OrderBy(x => x.PublishingDate).Reverse().ToHashSet();
        }
        else if (Cid != null)
        {
            var feeds = await _syndicationService.GetSyndicationsAsync(Cid == string.Empty ? null : Cid);
            var feedIds = feeds.Select(x => x.EncodedUrl);
            var feedItems = await _syndicationService.GetSyndicationItemsFromSyndicationsAsync(feedIds.ToArray());
            items = feedItems.Select(x => SyndicationItemData.FromModel(x)).OrderBy(x => x.PublishingDate).Reverse().ToHashSet();
        }
        _isLoading = false;
        await InvokeAsync(StateHasChanged);
    }
}