@using Newtonsoft.Json
@inherits FnzComponentBase

@code {
    [Parameter, Required] public FePlaylist Playlist { get; set; }
    [Parameter, Required] public int ListItemIndex { get; set; }
    [Parameter, Required] public int ListItemCount { get; set; }

    [Parameter] public EventCallback<Guid> EditPlaylist { get; set; } = EventCallback<Guid>.Empty;
    [Parameter] public EventCallback<Guid> DeletePlaylist { get; set; } = EventCallback<Guid>.Empty;

    private bool isExpand;
    private PlaylistExportDialog dlgExport;

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await base.OnAfterRenderAsync(firstRender);
        await JSRuntime.InvokeVoidAsync(Prefix + ".initDropZone", ElementId, DotNetRef, FnzConst.DragDropTypePlaylistItem);
        await JSRuntime.InvokeVoidAsync(Prefix + ".initDropZone", ElementId, DotNetRef, FnzConst.DragDropTypePlaylist);
        await JSRuntime.InvokeVoidAsync(Prefix + ".initDragSource", ElementId, DotNetRef, FnzConst.DragDropTypePlaylist);
        await JSRuntime.InvokeVoidAsync(Prefix + ".resolveSelectTextClickConflict", ElementId, DotNetRef);
    }

    private async Task DragMouseDown() => await JSRuntime.InvokeVoidAsync(Prefix + ".setDraggableOn", ElementId);

    private async Task DragMouseUp() => await JSRuntime.InvokeVoidAsync(Prefix + ".setDraggableOff", ElementId);


    [JSInvokable("FnzDragStartProvideContent")]
    public string FnzDragStartProvideContent(string dataType)
    {
        if (dataType != FnzConst.DragDropTypePlaylist) return null;
        var str = JsonConvert.SerializeObject(Playlist.Id);
        return str;
    }

    [JSInvokable("FnzDragDropContent")]
    public void FnzDragDropContent(string dataType, string content)
    {
        if (dataType == FnzConst.DragDropTypePlaylistItem)
        {
            var ds = JsonConvert.DeserializeObject<PlaylistDragSource>(content);
            if (string.IsNullOrWhiteSpace(ds?.Path)) return;
            PlaylistHelper.TrackMove(ds.PlaylistId, ds.TrackIndex, ds.Path, Playlist.Id, 0);
        }

        if (dataType == FnzConst.DragDropTypePlaylist)
        {
            var playlistId = JsonConvert.DeserializeObject<Guid>(content);
            if (playlistId == default) return;
            PlaylistHelper.ListMove(playlistId, ListItemIndex);
        }
    }
}

<div class="table-responsive">
    <table class="table w-100">
        <tbody>
            @if (Playlist != null)
            {
                var arr = PlaylistHelper[Playlist.Id];

                <tr id="@ElementId" class="table-primary">
                    <td style="width:0" @onclick="()=>{isExpand=!isExpand;}">
                        <button type="button" class="btn btn-primary p-2">
                            @if (isExpand)
                            {
                                <i class="bi bi-dash-square"></i>
                            }
                            else
                            {
                                <i class="bi bi-plus-square"></i>
                            }
                        </button>
                    </td>
                    <td class="text-start w-100 align-middle" @onclick="()=>{isExpand=!isExpand;}" colspan="3">
                        <div class="text-nowrap">@Playlist.Name</div>
                        <div class="text-nowrap text-muted">
                            (@arr.Count)
                            @arr.Sum(p=>DataSet.AllTracks.Where(q=>q.Path==p).Select(q=>q.Tag?.Duration??0).FirstOrDefault()).SecondToDur()
                            @arr.Sum(p=>DataSet.AllTracks.Where(q=>q.Path==p).Select(q=>q.Tag?.Length??0).FirstOrDefault()).BytesToFileSize()
                        </div>
                    </td>
                    <td>
                        @if (ListItemCount > 1)
                        {
                            var isFirst = ListItemIndex == 0;
                            var isLast = ListItemIndex == ListItemCount - 1;

                            <div class="dropstart">
                                <button type="button" class="btn btn-primary p-2" data-bs-toggle="dropdown" @onmousedown="DragMouseDown" @onmouseup="DragMouseUp">
                                    <i class="bi bi-arrow-down-up"></i>
                                </button>
                                <div class="dropdown-menu text-end p-1 text-nowrap" style="width: initial;min-width: initial;">
                                    <button class="btn btn-primary p-2" disabled="@isFirst" @onclick="()=>PlaylistHelper.ListMoveUp(ListItemIndex)">
                                        <i class="bi bi-arrow-bar-up"></i>
                                        Up
                                    </button>
                                    <button class="btn btn-primary p-2" disabled="@isLast" @onclick="()=>PlaylistHelper.ListMoveDown(ListItemIndex)">
                                        <i class="bi bi-arrow-bar-down"></i>
                                        Down
                                    </button>
                                </div>
                            </div>
                        }
                    </td>
                    <td>
                        <button type="button" class="btn btn-primary p-2" @onclick="()=>DownloadPlaylist(Playlist.Id)">
                            <i class="bi bi-download"></i>
                        </button>
                    </td>
                    <td>
                        <button type="button" class="btn btn-primary p-2" @onclick="()=>EditPlaylist.InvokeAsync(Playlist.Id)">
                            <i class="bi bi-pencil-square"></i>
                        </button>
                    </td>
                    <td>
                        <button type="button" class="btn btn-danger p-2" @onclick="()=>DeletePlaylist.InvokeAsync(Playlist.Id)">
                            <i class="bi bi-trash"></i>
                        </button>
                    </td>
                </tr>

                @if (isExpand)
                {
                    @foreach (var item in arr.KeepNoEmpty().WithIndex())
                    {
                        if (item.item != null)
                        {
                            var track = DataSet.AllTracks.FirstOrDefault(p => p.Path == item.item);
                            if (track != null)
                            {
                                <PlaylistTableItem PlaylistId="@Playlist.Id"
                                                   TrackIndex="@item.index"
                                                   TrackCount="@arr.Count"
                                                   Track="@track">
                                </PlaylistTableItem>
                            }
                            else
                            {
                                <PlaylistTableItemBrokenReference PlaylistId="@Playlist.Id"
                                                                  TrackIndex="@item.index"
                                                                  Path="@item.item">
                                </PlaylistTableItemBrokenReference>
                            }
                        }
                        else
                        {
                            <tr>
                                <td></td>
                                <td colspan="7" class="align-middle w-100">
                                    <div class="text-nowrap">- empty -</div>
                                </td>
                            </tr>
                        }
                    }
                }
            }
        </tbody>
    </table>
</div>

<PlaylistExportDialog @ref="dlgExport">
</PlaylistExportDialog>

@code {
    private void DownloadPlaylist(Guid playlistId)
    {
        dlgExport.Show(playlistId);
    }
}
