1
0
mirror of synced 2024-12-12 22:41:08 +01:00
GC-local-server-rewrite/WebUI/Pages/Dialogs/ChangePlayerNameDialog.razor
2023-02-21 22:45:51 +08:00

84 lines
2.6 KiB
Plaintext

@using System.Text.RegularExpressions
@using Shared.Dto.Api
@using Shared.Models
@using Throw
@inject HttpClient Client
@inject ILogger<ChangePlayerNameDialog> Logger
@{
#pragma warning disable CS8974
}
<MudDialog>
<TitleContent>
<MudText Typo="Typo.h6">
Change Player Name
</MudText>
</TitleContent>
<DialogContent>
<MudForm @bind-IsValid="IsValid">
<MudTextField Value="@Data.CardId" Label="CardId" ReadOnly="true"/>
<MudTextField @bind-Value="Data.PlayerName"
Immediate="true"
Counter="PLAYER_NAME_MAX_LENGTH"
MaxLength="PLAYER_NAME_MAX_LENGTH"
Validation="ValidatePlayerName"/>
</MudForm>
</DialogContent>
<DialogActions>
<MudButton OnClick="Cancel">Cancel</MudButton>
<MudButton Color="Color.Primary" OnClick="Submit" Disabled="@(!IsValid)">Confirm</MudButton>
</DialogActions>
</MudDialog>
@code {
[CascadingParameter]
MudDialogInstance MudDialog { get; set; } = null!;
[Parameter]
public ClientCardDto Data { get; set; } = null!;
private string originalName = string.Empty;
private bool IsValid { get; set; }
private const int PLAYER_NAME_MAX_LENGTH = 8;
protected override void OnInitialized()
{
base.OnInitialized();
originalName = new string(Data.PlayerName);
}
async Task Submit()
{
if (originalName.Equals(Data.PlayerName))
{
MudDialog.Close(DialogResult.Ok(true));
return;
}
Logger.LogInformation("Data is {CardId}, {Name}", Data.CardId, Data.PlayerName);
var response = await Client.PostAsJsonAsync("api/Profiles/PlayerName", Data);
var result = await response.Content.ReadFromJsonAsync<ServiceResult<bool>>();
result.ThrowIfNull();
Logger.LogInformation("SetPlayerName result is {Result}", result.Succeeded);
MudDialog.Close(DialogResult.Ok(result));
}
void Cancel()
{
Data.PlayerName = originalName;
MudDialog.Cancel();
}
private static string? ValidatePlayerName(string playerName)
{
const string pattern = @"^[a-zA-Z0-9!?,./\-+:<>_\\@*#&=() ]{1,8}$";
return playerName.Length switch
{
0 => "Player name cannot be empty!",
> PLAYER_NAME_MAX_LENGTH => "Player name cannot be longer than 8 characters!",
_ => !Regex.IsMatch(playerName, pattern) ? "Player name contains invalid character!" : null
};
}
}