@namespace OpenArchival.Blazor.FileViewer

@using Microsoft.Extensions.Logging
@using Microsoft.JSInterop
@using OpenArchival.DataAccess;
@using MudBlazor;

<MudCarousel Class="mud-width-full auto-height-carousel"
             Style="@($"height: {(_currentHeight > 0 ? $"{_currentHeight}px" : "400px")}; max-height: 80vh; {(MaxHeight > 0 ? $"max-height: {Math.Min(MaxHeight, 800)}px;" : "")}")"
             TData="object"
             AutoCycle=false
             @bind-SelectedIndex="SelectedIndex"
             ShowArrows="(FilePathListings.Count > 1)"
             ShowBullets="(FilePathListings.Count > 1)">
    @foreach (var file in FilePathListings.Select((value, i) => new { i, value }))
    {
        @if (!ShowUnsupportedFiles && FileViewerFactory.GetViewerComponent(file.value.OriginalName) == typeof(UnsupportedFileViewer))
        {
            continue; 
        }

        <MudCarouselItem @key="file.value" Class="@(file.i == SelectedIndex ? "mud-carousel-item-active" : "")">
            @if (file.i == SelectedIndex)
            {
                @CreateDynamicComponent(file.value)
            }
        </MudCarouselItem>
    }
</MudCarousel>

@inject ILogger<FileViewerCarousel> Logger;
@inject IJSRuntime JSRuntime;
@code {
    [Parameter]
    public bool ShowUnsupportedFiles { get; set; }

    [Parameter]
    public List<FilePathListing> FilePathListings { get; set; } = [];

    [Parameter]
    public int MaxHeight { get; set; } 

    public int SelectedIndex { get; set; }

    private int _currentHeight = 400;

    private void HandleHeightMeasured(int height)
    {
        if (height > 0 && height != _currentHeight)
        {
            _currentHeight = height;
            StateHasChanged();
        }
    }

    private RenderFragment CreateDynamicComponent(FilePathListing file)
    {
        return builder =>
        {
            Type componentType = FileViewerFactory.GetViewerComponent(file.OriginalName);
            builder.OpenComponent(0, componentType);
            builder.AddAttribute(1, "File", file);
            builder.AddAttribute(2, "OnHeightMeasured", EventCallback.Factory.Create<int>(this, HandleHeightMeasured));
            builder.CloseComponent();
        };
    }
}
