2022-11-19 15:36:29 +00:00
|
|
|
import 'package:flutter_bloc/flutter_bloc.dart';
|
|
|
|
|
2022-12-13 02:36:22 +00:00
|
|
|
import '../connection/ws_connection.dart';
|
|
|
|
|
2022-11-19 15:36:29 +00:00
|
|
|
class ConnectionCubit extends Cubit<ConnectionCubitState> {
|
|
|
|
static final ConnectionCubit _instance = ConnectionCubit._internal();
|
|
|
|
|
|
|
|
ConnectionCubit._internal() : super(ConnectionCubitState.init());
|
|
|
|
|
|
|
|
factory ConnectionCubit.getInstance() {
|
|
|
|
return ConnectionCubit();
|
|
|
|
}
|
|
|
|
|
|
|
|
factory ConnectionCubit() {
|
|
|
|
return _instance;
|
|
|
|
}
|
|
|
|
|
2024-05-20 13:34:20 +00:00
|
|
|
void connect(String playerID, String? passphrase) {
|
2024-05-21 16:48:06 +00:00
|
|
|
var connectedFuture =
|
|
|
|
ServerConnection.getInstance().connect(playerID, passphrase);
|
|
|
|
|
|
|
|
connectedFuture?.then((val) {
|
|
|
|
emit(ConnectionCubitState(
|
|
|
|
iAmConnected: true,
|
|
|
|
connectedToPhrase: passphrase,
|
|
|
|
opponentConnected: false));
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
void connectIfNotConnected(String playerID, String? passphrase) {
|
|
|
|
if (state.iAmConnected && state.connectedToPhrase == passphrase) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if (state.iAmConnected && state.connectedToPhrase != passphrase) {
|
|
|
|
disonnect().then((val) {
|
|
|
|
connect(playerID, passphrase);
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
connect(playerID, passphrase);
|
2024-05-20 13:34:20 +00:00
|
|
|
}
|
|
|
|
|
2024-05-20 15:21:25 +00:00
|
|
|
Future disonnect() async {
|
2024-05-21 16:48:06 +00:00
|
|
|
var disconnectFuture =
|
|
|
|
ServerConnection.getInstance().disconnectExistingConnection();
|
|
|
|
|
|
|
|
disconnectFuture.then(
|
|
|
|
(val) {
|
|
|
|
emit(ConnectionCubitState.init());
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
return disconnectFuture;
|
2023-06-29 23:49:18 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
void opponentConnected() {
|
2024-05-21 16:48:06 +00:00
|
|
|
emit(ConnectionCubitState(
|
|
|
|
iAmConnected: state.iAmConnected,
|
|
|
|
connectedToPhrase: state.connectedToPhrase,
|
|
|
|
opponentConnected: true));
|
2022-11-19 15:36:29 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
class ConnectionCubitState {
|
2024-05-21 16:48:06 +00:00
|
|
|
final bool iAmConnected;
|
|
|
|
final String? connectedToPhrase;
|
2023-06-29 23:49:18 +00:00
|
|
|
final bool opponentConnected;
|
2022-11-19 15:36:29 +00:00
|
|
|
|
2024-05-21 16:48:06 +00:00
|
|
|
ConnectionCubitState(
|
|
|
|
{required this.iAmConnected,
|
|
|
|
required this.connectedToPhrase,
|
|
|
|
required this.opponentConnected});
|
2022-11-19 15:36:29 +00:00
|
|
|
|
|
|
|
factory ConnectionCubitState.init() {
|
2024-05-21 16:48:06 +00:00
|
|
|
return ConnectionCubitState(
|
|
|
|
iAmConnected: false, connectedToPhrase: null, opponentConnected: false);
|
2022-11-19 15:36:29 +00:00
|
|
|
}
|
|
|
|
}
|