Files
Shogi/Shogi.Contracts/Api/Commands/MovePieceCommand.cs
2024-10-31 19:04:55 -05:00

81 lines
2.2 KiB
C#

using Shogi.Contracts.Types;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text.RegularExpressions;
namespace Shogi.Contracts.Api.Commands;
public partial class MovePieceCommand : IValidatableObject
{
/// <summary>
/// For serialization.
/// </summary>
public MovePieceCommand()
{
To = string.Empty;
}
/// <summary>
/// Move a piece on the board.
/// </summary>
public MovePieceCommand(string from, string to, bool isPromotion)
{
From = from;
To = to;
IsPromotion = isPromotion;
}
/// <summary>
/// Add a piece to the board from the hand.
/// </summary>
public MovePieceCommand(WhichPiece pieceFromHand, string to)
{
PieceFromHand = pieceFromHand;
To = to;
}
/// <summary>
/// Mutually exclusive with <see cref="From"/>.
/// Set this property to indicate moving a piece from the hand onto the board.
/// </summary>
public WhichPiece? PieceFromHand { get; set; }
/// <summary>
/// Board position notation, like A3 or G1
/// Mutually exclusive with <see cref="PieceFromHand"/>.
/// Set this property to indicate moving a piece from the board to another position on the board.
/// </summary>
public string? From { get; set; }
/// <summary>
/// Board position notation, like A3 or G1
/// </summary>
[Required]
public string To { get; set; }
public bool? IsPromotion { get; set; }
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (PieceFromHand.HasValue && !string.IsNullOrWhiteSpace(From))
{
yield return new ValidationResult($"{nameof(PieceFromHand)} and {nameof(From)} are mutually exclusive properties.");
}
if (PieceFromHand.HasValue && IsPromotion.HasValue)
{
yield return new ValidationResult($"{nameof(PieceFromHand)} and {nameof(IsPromotion)} are mutually exclusive properties.");
}
if (!BoardNotationRegex().IsMatch(To))
{
yield return new ValidationResult($"{nameof(To)} must be a valid board position, between A1 and I9");
}
if (!string.IsNullOrEmpty(From) && !BoardNotationRegex().IsMatch(From))
{
yield return new ValidationResult($"{nameof(From)} must be a valid board position, between A1 and I9");
}
}
[GeneratedRegex("[A-I][1-9]")]
private static partial Regex BoardNotationRegex();
}