@using SharpRss.Models;
@using MudBlazor.Utilities
@using Serilog
@using SharpRss.Services
@using WebSharpRSS.Models;
@using ToolQit.Extensions;

@inject SyndicationService _syndicationService
@inject NavigationManager _navigation

<MudStack Spacing="2">
    <MudTreeView Color="Color.Success" Items="_guideItems" @bind-SelectedValue="SelectedItem" Hover="true">
        <ItemTemplate>
            <MudTreeViewItem @bind-Expanded="@context.IsExpanded" Value="@context" Items="@context.Children" CanExpand="@context.HasChildren" @onclick="ItemClicked">
                <Content>
                    <div style="display: grid; grid-template-columns: 1fr auto; align-items: center; width: 100%">
                        <div class="d-flex align-center">
                            <MudTreeViewItemToggleButton ExpandedChanged="@(() => ExpandedChanged(context))" Loading="@context.Loading" Visible="@context.HasChildren" LoadingIconColor="Color.Info"/>
                            @if (context.FaviconUrl == null && context.Icon != null)
                            {
                                <MudIcon Icon="@context.Icon" Style="@($"color:{context.CategoryModel?.HexColor ?? _theme.Palette.Primary.Value}")"/>
                            }
                            else
                            {
                                <MudImage Src="@context.FaviconUrl" ObjectFit="ObjectFit.ScaleDown"/>
                            }
                            <MudText Class="ml-2">@context.Title</MudText>
                        </div>
                        <MudText Class="d-inline-flex align-self-end" Color="Color.Secondary" Typo="Typo.overline">@context.TotalItems</MudText>
                    </div>
                </Content>
            </MudTreeViewItem>
        </ItemTemplate>
    </MudTreeView>
</MudStack>

@code {
    private MudTheme _theme = new MudTheme();
    private readonly HashSet<TreeItemData> _guideItems = new HashSet<TreeItemData>();
    private TreeItemData? _selectedItem;
    private TreeItemData? SelectedItem 
    {
        get => _selectedItem;
        set
        {
            _selectedItem = value;
            ItemClicked();
        }
    }
    private void ItemClicked()
    {
        if (_selectedItem == null) return;
        if (_selectedItem.SyndicationModel != null)
        {
            _navigation.NavigateTo($"/list?fid={_selectedItem.SyndicationModel.EncodedUrl}");
        }
        else if (_selectedItem.CategoryModel != null)
        {
            _navigation.NavigateTo($"/list?cid={_selectedItem.CategoryModel.Id}");
        }
    }
    private async void ExpandedChanged(TreeItemData treeItemData)
    {
        treeItemData.Loading = true;
        if (treeItemData.CategoryModel != null)
            treeItemData.Children = ModelToTreeItem(treeItemData.CategoryModel.Syndications);
        treeItemData.IsExpanded = !treeItemData.IsExpanded;
        treeItemData.Loading = false;
        StateHasChanged();
    }
    protected override async void OnInitialized()
    {
        Log.Verbose("Loading guide data...");
        HashSet<object> items = await _syndicationService.GetCategoriesAndSyndicationsAsync();
        _guideItems.UnionWith(ModelToTreeItem(items));

        StateHasChanged();
        Log.Verbose("Guide initialized!");
    }
    private HashSet<TreeItemData> ModelToTreeItem<T>(HashSet<T> model) => model.Select(x => x is CategoryModel model ? new TreeItemData(model) : x is SyndicationModel feedModel ? new TreeItemData(feedModel) : throw new ArgumentException("Item arg is invalid!")).ToHashSet();
}