import 'dart:convert'; import 'dart:developer'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:go_router/go_router.dart'; import 'package:http/http.dart' as http; import 'package:http/http.dart'; import 'package:mchess/api/register.dart'; import 'package:mchess/connection_cubit/connection_cubit.dart'; import 'package:mchess/pages/chess_game.dart'; class JoinGameWidget extends StatefulWidget { const JoinGameWidget({ super.key, }); @override State createState() => _JoinGameWidgetState(); } class _JoinGameWidgetState extends State { final myController = TextEditingController(); late Future joinGameFuture; @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return Scaffold( body: TextField( controller: myController, decoration: InputDecoration( hintText: 'Enter passphrase here', suffixIcon: IconButton( onPressed: () { joinGameFuture = joinPrivateGame(); switchToGame(joinGameFuture); }, icon: const Icon(Icons.check), )), ), floatingActionButton: FloatingActionButton( onPressed: () { context.push('/'); }, child: const Icon(Icons.cancel), ), ); } void switchToGame(Future resp) { resp.then((value) { if (value == null) return; var chessGameArgs = ChessGameArguments( lobbyID: value.lobbyID!, playerID: value.playerID!, passphrase: value.passphrase); ConnectionCubit.getInstance().connect( value.playerID!.uuid, value.lobbyID!.uuid, value.passphrase, ); context.push('/game', extra: chessGameArgs); }); } Future joinPrivateGame() async { String addr; Response response; // server expects us to send the passphrase var info = PlayerInfo( playerID: null, lobbyID: null, passphrase: myController.text); if (kDebugMode) { addr = 'http://localhost:8080/api/joinPrivate'; } else { addr = 'https://chess.sw-gross.de:9999/api/joinPrivate'; } try { response = await http.post(Uri.parse(addr), body: jsonEncode(info), headers: {"Accept": "application/json"}); } catch (e) { log(e.toString()); if (!context.mounted) return null; const snackBar = SnackBar( backgroundColor: Colors.amberAccent, content: Text("mChess server is not responding. Try again or give up"), ); Future.delayed(const Duration(seconds: 2), () { ScaffoldMessenger.of(context).clearSnackBars(); ScaffoldMessenger.of(context).showSnackBar(snackBar); context.pop(); }); return null; } if (response.statusCode == 200) { var info = PlayerInfo.fromJson(jsonDecode(response.body)); log('Player info received from server: '); log('lobbyID: ${info.lobbyID}'); log('playerID: ${info.playerID}'); log('passphrase: ${info.passphrase}'); return info; } return null; } }