dth-pingpong-mobileapp/lib/pages/views/joinmatch.dart
2024-12-23 21:48:34 +01:00

214 lines
6.4 KiB
Dart

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import '../../globals.dart';
class JoinMatchPage extends StatefulWidget {
@override
_JoinMatchPageState createState() => _JoinMatchPageState();
}
class _JoinMatchPageState extends State<JoinMatchPage> {
TextEditingController _matchIdController = TextEditingController();
bool _isJoined = false;
bool _isLoading = false;
int _player1Score = 0;
int _player2Score = 0;
String? _matchId;
final String _joinMatchApiUrl = '$apiurl/joinmatch';
final String _endMatchApiUrl = '$apiurl/endmatch';
Future<void> _joinMatch() async {
setState(() {
_isLoading = true;
});
final prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('token');
final String matchId = _matchIdController.text;
if (token == null) {
_showToast('No token found. Please login again.');
setState(() {
_isLoading = false;
});
return;
}
try {
final response = await http.post(
Uri.parse(_joinMatchApiUrl),
headers: {'Content-Type': 'application/json'},
body: json.encode({'token': token, 'match_id': int.parse(matchId)}),
);
if (response.statusCode == 200) {
setState(() {
_isJoined = true;
_player1Score = 0;
_player2Score = 0;
_matchId = matchId;
});
_showToast('Joined match successfully!');
} else {
_showToast('Failed to join match.');
}
} catch (e) {
_showToast('Error: $e');
} finally {
setState(() {
_isLoading = false;
});
}
}
void _updateScore(int player, int delta) {
setState(() {
if (player == 1) {
_player1Score += delta;
} else if (player == 2) {
_player2Score += delta;
}
});
}
Future<void> _endMatch() async {
setState(() {
_isLoading = true;
});
final prefs = await SharedPreferences.getInstance();
final String? token = prefs.getString('token');
if (token == null) {
_showToast('No token found. Please login again.');
setState(() {
_isLoading = false;
});
return;
}
try {
final response = await http.post(
Uri.parse(_endMatchApiUrl),
headers: {'Content-Type': 'application/json'},
body: json.encode({
'match_id': int.parse(_matchId!),
'player1_score': _player1Score,
'player2_score': _player2Score,
}),
);
if (response.statusCode == 200) {
_showToast('Match ended successfully!');
Navigator.pop(context);
} else {
_showToast('Failed to end match.');
}
} catch (e) {
_showToast('Error: $e');
} finally {
setState(() {
_isLoading = false;
});
}
}
void _showToast(String message) {
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text(message)),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Join Match'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: _isLoading
? Center(child: CircularProgressIndicator())
: _isJoined
? Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
icon: Icon(Icons.remove),
onPressed: () => _updateScore(1, -1),
),
Text(
'Player 1 Score: $_player1Score',
style: TextStyle(fontSize: 20),
),
IconButton(
icon: Icon(Icons.add),
onPressed: () => _updateScore(1, 1),
),
],
),
SizedBox(height: 16),
// Player 2 Score Controls
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
icon: Icon(Icons.remove),
onPressed: () => _updateScore(2, -1),
),
Text(
'Player 2 Score: $_player2Score',
style: TextStyle(fontSize: 20),
),
IconButton(
icon: Icon(Icons.add),
onPressed: () => _updateScore(2, 1),
),
],
),
SizedBox(height: 32),
// End Match Button
ElevatedButton(
onPressed: _endMatch,
child: Text('End Match'),
),
],
)
: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
// Match ID Text Field
TextField(
controller: _matchIdController,
decoration: InputDecoration(
labelText: 'Enter Match ID',
border: OutlineInputBorder(),
),
),
SizedBox(height: 16),
// Join Match Button
ElevatedButton(
onPressed: () {
if (_matchIdController.text.isNotEmpty) {
_joinMatch();
} else {
_showToast('Please enter a Match ID.');
}
},
child: Text('Join Match'),
),
],
),
),
);
}
}