@inject ISnackbar Snackbar

<MudDialog>
    <TitleContent>
        <MudText Typo="Typo.h6">
            Danh sách script sẽ xóa
        </MudText>
    </TitleContent>
    <DialogContent>
        <div class="d-flex flex-column ms-3 overflow-y-scroll overflow-x-auto" style="height: 200px; width: 500px;">
            @foreach (var file in DeleteList)
            {
                <span>
                    @file
                </span>
            }
        </div>
    </DialogContent>
    <DialogActions>
        <MudButton OnClick="OnCancel">Cancel</MudButton>
        <MudButton Color="Color.Primary" OnClick="OnDelete">Delete</MudButton>
    </DialogActions>
</MudDialog>

@code {
    [CascadingParameter]
    private IMudDialogInstance Dialog { get; set; } = null!;

    [Parameter]
    public ScriptWorkspace Workspace { get; set; } = null!;

    private IEnumerable<string> DeleteList = [];

    protected override void OnInitialized()
    {
        base.OnInitialized();

        if (Workspace.SelectedFile is not null)
        {
            DeleteList = [Workspace.SelectedFile.Path];
            StateHasChanged();
        }
        else if (Workspace.SelectedFolder is not null)
        {
            DeleteList = GetListFromFolder(Workspace.SelectedFolder);
            StateHasChanged();
        }
    }


    private IEnumerable<string> GetListFromFolder(ScriptFolderModel folder)
    {
        var list = new List<string>();
        list.Add(folder.Path);

        foreach (var dir in folder.Folders)
        {
            list.AddRange(GetListFromFolder(dir));
        }

        foreach (var file in folder.Files)
        {
            list.Add(file.Path);
        }

        return list;
    }

    private void OnCancel() => Dialog.Cancel();

    private async Task OnDelete()
    {
        if (Workspace.SelectedFile is not null)
        {
            var result = await Workspace.DeleteFile(Workspace.SelectedFile);
            if (result.IsSuccess)
            {
                Dialog.Close();
            }
            else
            {
                Snackbar.Add(result.Message, Severity.Error);
            }
        }
        else if (Workspace.SelectedFolder is not null)
        {
            var result = await Workspace.DeleteFolder(Workspace.SelectedFolder);
            if (result.IsSuccess)
            {
                Dialog.Close();
            }
            else
            {
                Snackbar.Add(result.Message, Severity.Error);
            }
        }
    }
}
