mchess-client/lib/api/websocket_message.dart

80 lines
1.8 KiB
Dart
Raw Permalink Normal View History

2023-06-08 15:10:48 +00:00
import 'package:mchess/api/move.dart';
enum MessageType {
move,
invalidMove,
2023-06-08 15:10:48 +00:00
colorDetermined;
String toJson() => name;
static MessageType fromJson(String json) => values.byName(json);
}
enum ApiColor {
black,
white;
String toJson() => name;
static ApiColor fromJson(String json) => values.byName(json);
}
class ApiWebsocketMessage {
final MessageType type;
final ApiMove? move;
final ApiColor? color;
final String? reason;
final String? position;
final ApiCoordinate? squareInCheck;
2023-06-08 15:10:48 +00:00
ApiWebsocketMessage({
required this.type,
required this.move,
required this.color,
required this.reason,
required this.position,
required this.squareInCheck,
});
2023-06-08 15:10:48 +00:00
factory ApiWebsocketMessage.fromJson(Map<String, dynamic> json) {
final type = MessageType.fromJson(json['messageType']);
ApiWebsocketMessage ret;
switch (type) {
case MessageType.colorDetermined:
ret = ApiWebsocketMessage(
type: type,
move: null,
color: ApiColor.fromJson(json['color']),
reason: null,
position: null,
squareInCheck: null,
);
2023-06-08 15:10:48 +00:00
break;
case MessageType.move:
2023-06-08 15:10:48 +00:00
ret = ApiWebsocketMessage(
type: type,
move: ApiMove.fromJson(json['move']),
color: null,
reason: null,
position: json['position'],
squareInCheck: json['squareInCheck']
);
break;
case MessageType.invalidMove:
ret = ApiWebsocketMessage(
type: type,
move: ApiMove.fromJson(json['move']),
color: null,
reason: json['reason'],
position: null,
squareInCheck: json['squareInCheck'],
);
2023-06-08 15:10:48 +00:00
}
return ret;
}
2023-07-03 17:41:12 +00:00
Map<String, dynamic> toJson() => {
'messageType': type,
'move': move,
'color': color,
};
2023-06-08 15:10:48 +00:00
}