@using MudBlazor
@using OpenArchival.DataAccess
@using Microsoft.AspNetCore.Components;

@namespace OpenArchival.Blazor.ArtifactGroupingDisplay

@page "/sr/{StringId}"

<MudLink Href="@($"/archive/{Id}")" Target="_blank" Style="text-decoration: none; color: inherit;">
    <MudCard Style="@($"cursor: pointer; height: {Height}px; display: flex; flex-direction: column;")">
        @if (_displayImageId >= 0)
        {
            <MudCardMedia Image="@($"/api/files/{_displayImageId}")" Height="150" />
        }

        <MudCardContent Style="flex-grow: 1; overflow-y: clip;">
            @if (ArtifactGrouping is not null)
            {
                <MudText Typo="Typo.h5">@ArtifactGrouping.Title</MudText>
                <MudText Typo="Typo.body2">@ArtifactGrouping.Description</MudText>
            }
        </MudCardContent>
    </MudCard>
</MudLink>
@inject IArtifactGroupingProvider GroupingProvider;
@inject NavigationManager NavigationManager;
@code {
    [Parameter]
    public ArtifactGrouping? ArtifactGrouping { get; set; } 

    private int _displayImageId = -1;

    /// <summary>
    /// Allows the component to fetch its own data from the database. If set it will query the database for an artifact groupign with this id
    /// </summary>
    [Parameter]
    public int Id { get; set; } = 0;

    [Parameter]
    public string? StringId { get; set; }

    [Parameter]
    public int Height { get; set; } = 350;

    protected override async Task OnParametersSetAsync()
    {
        if (!string.IsNullOrEmpty(StringId))
        {
            if (!int.TryParse(StringId, out int parsedId)) 
            {
                NavigationManager.NavigateTo($"/grouping-not-found/{System.Net.WebUtility.UrlEncode("Failed to parse ID")}");
            } else
            {
                Id = parsedId;
            }
        }

        if (ArtifactGrouping is null)
        {
            var grouping = await GroupingProvider.GetGroupingAsync(Id);

            if (grouping is null)
            {
                NavigationManager.NavigateTo("/grouping-not-found");
            }

            ArtifactGrouping = grouping!;
        }

        if (ArtifactGrouping is not null)
        {
            if (ArtifactGrouping.ChildArtifactEntries.Count > 0 && ArtifactGrouping.ChildArtifactEntries[0].Files.Count > 0)
            {
                _displayImageId = ArtifactGrouping.ChildArtifactEntries[0].Files[0].Id;
            }
            Id = ArtifactGrouping.Id;
        }

        StateHasChanged();
    }
}
