@using RobotNet.WebApp.Scripts.Components.Dialogs

@inject IDialogService DialogService
@inject ISnackbar Snackbar

<div class="sidebar-actions">
    <span></span>
    <div class="d-flex flex-row">
        <ActionButton Icon="mdi-content-save-all text-primary" Tooltip="Save all" OnClick="SaveAllFiles" />
        <ActionButton Icon="mdi-file-plus-outline" Tooltip="New file" OnClick="OpenDialogCreateNewFile" />
        <ActionButton Icon="mdi-folder-plus-outline" Tooltip="New folder" OnClick="OpenDialogCreateNewFolder" />
    </div>
</div>

@code {
    [CascadingParameter]
    private ScriptWorkspace Workspace { get; set; } = null!;

    private async Task OpenDialogCreateNewFile()
    {
        var parentPath = Workspace.SelectedFolder?.Path ?? "";

        var parameters = new DialogParameters<CreateNewFileOrFolderDialog>()
        {
            {x => x.FolderName, parentPath},
        };

        var dialog = await DialogService.ShowAsync<CreateNewFileOrFolderDialog>("Create new file", parameters);
        var resultDialog = await dialog.Result;

        if (resultDialog is null || resultDialog.Canceled || resultDialog.Data is not string fileName) return;

        fileName = fileName.EndsWith(".cs") ? fileName : fileName + ".cs";
        var result = await Workspace.CreateNewFile(fileName);

        if (!result.IsSuccess)
        {
            Snackbar.Add(result.Message, Severity.Error);
        }
    }
    private async Task OpenDialogCreateNewFolder()
    {

        var parentPath = Workspace.SelectedFolder?.Path ?? "";
        var parameters = new DialogParameters<CreateNewFileOrFolderDialog>()
        {
            {x => x.FolderName, parentPath},
            {x => x.IsFolder, true },
        };

        var dialog = await DialogService.ShowAsync<CreateNewFileOrFolderDialog>("Create new folder", parameters);
        var resultDialog = await dialog.Result;

        if (resultDialog is null || resultDialog.Canceled || resultDialog.Data is not string folderName) return;

        var result = await Workspace.CreateNewFolder(folderName);

        if (!result.IsSuccess)
        {
            Snackbar.Add(result.Message, Severity.Error);
        }
    }

    private async Task SaveAllFiles()
    {
        var results = await Workspace.SaveAllAsync();
        foreach(var result in results)
        {
            if (!result.IsSuccess)
            {
                Snackbar.Add(result.Message, Severity.Error);
            }
        }
    }
}
