@inherits ViewBase
@code {

    public static App Instance { get; private set; }

    [Inject]
    private FnzDataSetHelper DataSetHelper { get; set; }

    private bool isLoading = true;
    private string loadingErrorMessage;

    private ProgressBar progressBar1;
    private ProgressBar progressBar2;
    private ProgressBar progressBar3;
    private ProgressBar progressBar4;

    private SettingDialog dlgSetting;
    private PlaylistAddDialog dlgPlaylistAdd;

    private enum ViewNames { Browse, Search, Playlists }
    private ViewNames CurrentView { get => LocalStorage.GetByCallerMemberName<ViewNames>(); set => LocalStorage.SetByCallerMemberName(value); }

    protected override async Task OnInitializedAsync()
    {
        Instance = this;
        if (CurrentView == 0) CurrentView = ViewNames.Browse;
        await base.OnInitializedAsync();
        await LoadData();
    }
}

<SettingDialog @ref="dlgSetting" ReloadData="async ()=>await LoadData()" />

<div class="container" style="margin-bottom: @(BottomBarHeight)px">

    <a style="float: right" href="/classic-index">Back OLD Home Page</a>
    <h3>Blazor WASM UI</h3>

    <ul class="nav nav-tabs justify-content-center nav-fill" id="MainNavBar">
        @foreach (ViewNames item in Enum.GetValues(typeof(ViewNames)))
        {
            <li class="nav-item">
                <button class="nav-link @(item == CurrentView ? "active" : "")" type="button" @onclick="() => CurrentView = item">
                    @item
                </button>
            </li>
        }
        <li class="nav-item" role="presentation">
            <button class="nav-link" type="button" role="tab" @onclick="() => dlgSetting.Show()">
                <i class="bi bi-gear"></i>
            </button>
        </li>
    </ul>

    @if (isLoading)
    {
        @if (loadingErrorMessage != null)
        {
            <div class="p-3">
                <span class="bi bi-x-circle text-danger" role="status" />
                <span>@loadingErrorMessage</span>
            </div>
        }
        else
        {
            <div class="p-3">
                <ProgressBar @ref="progressBar1" Throttle="500"></ProgressBar>
            </div>
            <div class="p-3">
                <ProgressBar @ref="progressBar2" Throttle="500"></ProgressBar>
            </div>
            <div class="p-3">
                <ProgressBar @ref="progressBar3" Throttle="500"></ProgressBar>
            </div>
            <div class="p-3">
                <ProgressBar @ref="progressBar4" Throttle="500"></ProgressBar>
            </div>
        }
    }

    @if (!isLoading)
    {
        switch (CurrentView)
        {
            case ViewNames.Browse:
                <BrowseView></BrowseView>
                break;
            case ViewNames.Search:
                <SearchView></SearchView>
                break;
            case ViewNames.Playlists:
                <PlaylistView></PlaylistView>
                break;
        }
    }

    <PlaylistAddDialog @ref="dlgPlaylistAdd"></PlaylistAddDialog>

</div>

@code {
    private async Task LoadData()
    {
        isLoading = true;
        StateHasChanged();
        await Task.Delay(10);

        await progressBar1.SetProgress(0, "Waiting server ready...", true);
        await progressBar2.SetProgress(0, "Pending load fileset...", true);
        await progressBar3.SetProgress(0, "Pending load tags...", true);
        await progressBar4.SetProgress(0, "Pending parse models...", true);

        StateHasChanged();
        await Task.Delay(10);

        try
        {
            do
            {
                var r = await ApiClient.GetProgressAsync();
                await progressBar1.SetProgress((float)r.LoadedTags / r.TotalTrackCount, $"Waiting server ready {r.LoadedTags}/{r.TotalTrackCount}");
                if (r?.IsLoading == false)
                {
                    await progressBar1.SetProgress(100, "Waiting server ready...OK", true);
                    break;
                }
                await Task.Delay(1000);
            } while (true);

            StateHasChanged();
            await Task.Delay(10);

            await DataSetHelper.InitFeModulesAsync(new[] { progressBar2, progressBar3, progressBar4, });

            StateHasChanged();
            await Task.Delay(500);

            isLoading = false;
        }
        catch (Exception ex)
        {
            loadingErrorMessage = ex.Message;
        }
    }

    public void ShowAddTrackToPlaylistDialog(FeTrack track) => dlgPlaylistAdd.Show(track);
}

@if (requestedPlay)
{
    <style>
        .bottom-bar {
            pointer-events: none;
            gap: 0;
        }

            .bottom-bar *:not(div) {
                pointer-events: auto;
            }

        .player-video {
            max-height: 25vh;
        }

        .player-audio {
            height: 60px;
        }
    </style>
    <div id="@(ElementId)-bottom-bar" class="bottom-bar fixed-bottom d-flex flex-wrap align-content-end flex-column-reverse" style="z-index: 4096;">
        <FnzVideo @ref="player" @onloadedmetadata="@PlayerLoaded" class="@PlayerCssClass" src="@currentPlayingUrl" autoplay controls playsinline></FnzVideo>
        <div class="text-end">
            <button class="btn btn-secondary text-nowrap" type="button" @onclick="@StopAndClose">
                <i class="bi bi-x-circle"></i> Stop and close
            </button>
            @*<div class="btn-group dropup">
                <button class="align-bottom btn btn-secondary dropdown-toggle" type="button" data-bs-toggle="dropdown">
                    <i class="bi bi-card-list"></i>
                </button>
                <div class="dropdown-menu">
                    <div class="text-center"><a class="btn-link" @onclick="@StopAndClose">Stop and close</a></div>
                </div>
            </div>*@
            @*<button class="btn btn-secondary" type="button">
                <i class="bi bi-chevron-bar-left"></i>
            </button>
            <button class="btn btn-secondary" type="button">
                <i class="bi bi-chevron-bar-right"></i>
            </button>*@
        </div>
    </div>
}

@code {
    public Task PlayTrack(FeTrack track) => PlayTrack(track.Path);

    private void StopAndClose()
    {
        currentPlayingUrl = null;
        StateHasChanged();
        requestedPlay = false;
        StateHasChanged();
        BottomBarHeight = 0;
        StateHasChanged();
        BottomBarHeightChanged?.Invoke();
    }
}

@code {
    private bool requestedPlay;
    private string currentPlayingUrl;

    public Action BottomBarHeightChanged;
    public int BottomBarHeight { get; private set; }

    private FnzVideo player;
    private bool isPlayAudio;
    private string PlayerCssClass => "w-100" + (isPlayAudio ? " player-audio" : " player-video");

    private async Task PlayTrack(string path)
    {
        if (player != null) await player.Reset();
        currentPlayingUrl = path;
        requestedPlay = true;
        StateHasChanged();
    }

    private async Task PlayerLoaded(EventArgs args)
    {
        await player.Play();
        isPlayAudio = await player.CheckIsAudioOnly();
        BottomBarHeight = await JSRuntime.InvokeAsync<int>(Prefix + ".getClientHeight", ElementId + "-bottom-bar");
        StateHasChanged();
        BottomBarHeightChanged?.Invoke();
    }

}
