import 'package:flutter_bloc/flutter_bloc.dart'; import '../connection/ws_connection.dart'; class ConnectionCubit extends Cubit { static final ConnectionCubit _instance = ConnectionCubit._internal(); ConnectionCubit._internal() : super(ConnectionCubitState.init()); factory ConnectionCubit.getInstance() { return ConnectionCubit(); } factory ConnectionCubit() { return _instance; } void connect(String playerID, String? passphrase) { 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); } Future disonnect() async { var disconnectFuture = ServerConnection.getInstance().disconnectExistingConnection(); disconnectFuture.then( (val) { emit(ConnectionCubitState.init()); }, ); return disconnectFuture; } void opponentConnected() { emit(ConnectionCubitState( iAmConnected: state.iAmConnected, connectedToPhrase: state.connectedToPhrase, opponentConnected: true)); } } class ConnectionCubitState { final bool iAmConnected; final String? connectedToPhrase; final bool opponentConnected; ConnectionCubitState( {required this.iAmConnected, required this.connectedToPhrase, required this.opponentConnected}); factory ConnectionCubitState.init() { return ConnectionCubitState( iAmConnected: false, connectedToPhrase: null, opponentConnected: false); } }