summaryrefslogtreecommitdiff
path: root/lib/scorekeeper.dart
blob: b5234669ce3ffbd35c828c93068315a9fa3fe1a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert';

class ScoreKeeper extends StatefulWidget {
  final bool isNewGame;
  final List<String>? playerNames;
  final Map<int, int>? pars;
  final Map<int, List<int>>? scores;
  final DateTime? gameCreationTime;

  const ScoreKeeper({
    super.key,
    this.isNewGame = false,
    this.playerNames,
    this.pars,
    this.scores,
    this.gameCreationTime,
  });

  @override
  ScoreKeeperState createState() => ScoreKeeperState();
}

class ScoreKeeperState extends State<ScoreKeeper> {
  late List<String> playerNames;
  late Map<int, int> pars;
  late Map<int, List<int>> scores;
  late DateTime gameCreationTime;
  late int _numberOfHoles;

  @override
  void initState() {
    super.initState();
    if (widget.isNewGame) {
      _numberOfHoles = 1;
      playerNames = [];
      pars = {1: 0};
      scores = {
        1: List.generate(playerNames.length, (_) => 0, growable: true),
      };
      gameCreationTime = DateTime.now();
      WidgetsBinding.instance.addPostFrameCallback((_) {
        _askForPlayerNames();
      });
    }
    else {
      // Use loaded data or initialize with default values
      playerNames = widget.playerNames ?? [];
      pars = widget.pars ?? {1: 0};
      scores = widget.scores ?? {
        1: List.generate(playerNames.length, (_) => 0, growable: true),
      };
      gameCreationTime = widget.gameCreationTime ?? DateTime.now();
      _numberOfHoles = scores.length;
    }
  }

  Future<void> _askForPlayerNames() async {
    TextEditingController controller = TextEditingController();
    return showDialog<void>(
      context: context,
      barrierDismissible: false, // User must tap a button to close the dialog
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Enter Player Names'),
          content: SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                const Text('Please enter player names, separated by commas.'),
                TextField(
                  controller: controller,
                ),
              ],
            ),
          ),
          actions: <Widget>[
            TextButton(
              child: const Text('Submit'),
              onPressed: () {
                // Splitting the input text by commas to get individual names
                setState(() {
                  playerNames = controller.text
                      .split(',')
                      .map((name) => name.trim())
                      .toList();
                });
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  Future<void> _saveGame() async {
    final prefs = await SharedPreferences.getInstance();
    final String timestamp = gameCreationTime.toIso8601String();
    final String gameKey = 'game_$timestamp'; // Unique key for each game

    // Convert maps with int keys to maps with String keys for JSON encoding
    final Map<String, int> parsAsStringKeys = pars.map((k, v) => MapEntry(k.toString(), v));
    final Map<String, List<int>> scoresAsStringKeys = scores.map((k, v) => MapEntry(k.toString(), v));

    final Map<String, dynamic> gameData = {
      'playerNames': playerNames,
      'pars': parsAsStringKeys,
      'scores': scoresAsStringKeys,
      'creationTime': timestamp,
    };

    await prefs.setString(gameKey, jsonEncode(gameData));
  }

  void _confirmDeleteGame(BuildContext context) {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text("Delete Game"),
          content: const Text("Are you sure you want to delete this game? This action cannot be undone."),
          actions: <Widget>[
            TextButton(
              child: const Text("Cancel"),
              onPressed: () {
                Navigator.of(context).pop(); // Close the dialog
              },
            ),
            TextButton(
              child: const Text("Delete"),
              onPressed: () {
                _deleteGame();
                Navigator.of(context).pop(); // Close the dialog
                Navigator.of(context).pop(); // Return to the main menu
              },
            ),
          ],
        );
      },
    );
  }

  Future<void> _deleteGame() async {
    final prefs = await SharedPreferences.getInstance();
    final String timestamp = gameCreationTime.toIso8601String();
    final String gameKey = 'game_$timestamp'; // Unique key for each game
    await prefs.remove(gameKey); // Assuming game data is saved with this key
  }

  void _showHoleDetailsDialog(int holeNumber) {
    // Initialize text editing controllers for par and scores
    TextEditingController parController =
    TextEditingController(text: pars[holeNumber]?.toString());
    Map<String, TextEditingController> scoreControllers = {};
    for (var playerName in playerNames) {
      int playerIndex = playerNames.indexOf(playerName);
      scoreControllers[playerName] = TextEditingController(
          text: scores[holeNumber] != null &&
              scores[holeNumber]!.length > playerIndex
              ? scores[holeNumber]![playerIndex].toString()
              : '');
    }

    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('Details for Hole $holeNumber'),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                TextField(
                  controller: parController,
                  decoration: const InputDecoration(labelText: "Par"),
                  keyboardType: TextInputType.number,
                ),
                ...playerNames.map((name) => TextField(
                  controller: scoreControllers[name]!,
                  decoration: InputDecoration(labelText: "$name's Score"),
                  keyboardType: TextInputType.number,
                )),
              ],
            ),
          ),
          actions: <Widget>[
            TextButton(
              child: const Text('Save'),
              onPressed: () {
                // Save the entered par and scores
                setState(() {
                  pars[holeNumber] = int.tryParse(parController.text) ?? 0;
                  scores[holeNumber] = playerNames
                      .map((name) =>
                  int.tryParse(scoreControllers[name]!.text) ?? 0)
                      .toList();
                });
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  Future<void> _editPlayerNames() async {
    TextEditingController nameController = TextEditingController(
      text: playerNames.join(', '),
    );

    await showDialog<void>(
      context: context,
      barrierDismissible: false, // User must tap a button to close the dialog
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Edit Player Names'),
          content: TextField(
            controller: nameController,
            decoration: const InputDecoration(hintText: 'Player 1, Player 2'),
          ),
          actions: <Widget>[
            TextButton(
              child: const Text('OK'),
              onPressed: () {
                final List<String> newNames = nameController.text
                    .split(',')
                    .map((name) => name.trim())
                    .toList();
                setState(() {
                  // Detect new players and add them
                  for (String newName in newNames) {
                    if (!playerNames.contains(newName)) {
                      playerNames.add(newName); // Add new player name
                      // Add a zero score for the new player in each hole
                      scores.forEach((hole, playerScores) {
                        // Ensure the scores list for each hole is growable
                        List<int> growableScores = List<int>.from(playerScores);
                        growableScores.add(
                            0); // Initialize with zero score for new player
                        scores[hole] =
                            growableScores; // Update with the modified scores list
                      });
                    }
                  }
                });
                Navigator.of(context).pop();
              },
            ),
          ],
        );
      },
    );
  }

  void _deleteLastHole() {
    if (scores.isEmpty) return; // No holes to delete

    final lastHoleScores = scores[_numberOfHoles - 1];
    final isAllZeros =
        lastHoleScores != null && lastHoleScores.every((score) => score == 0);

    if (isAllZeros) {
      // If all scores are zeros, delete the last hole without confirmation
      setState(() {
        _numberOfHoles--;
        pars.remove(_numberOfHoles + 1);
        scores.remove(_numberOfHoles + 1);
      });
    } else {
      // If any score is not zero, ask for confirmation
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: const Text('Delete Last Hole?'),
            content: const Text(
                'This hole has scores. Are you sure you want to delete it?'),
            actions: <Widget>[
              TextButton(
                child: const Text('Cancel'),
                onPressed: () => Navigator.of(context).pop(),
              ),
              TextButton(
                child: const Text('Delete'),
                onPressed: () {
                  setState(() {
                    _numberOfHoles--;
                    pars.remove(_numberOfHoles + 1);
                    scores.remove(_numberOfHoles + 1);
                  });
                  Navigator.of(context).pop();
                },
              ),
            ],
          );
        },
      );
    }
  }

  Widget _buildHoleDetails(int holeNumber) {
    String scoreText;

    if (scores[holeNumber] != null) {
      scoreText = 'Par: ${pars[holeNumber]}';
      List<String> scoreDetails = [];
      for (int i = 0; i < playerNames.length; i++) {
        final playerName = playerNames[i];
        final playerScore = scores[holeNumber]!.length > i
            ? scores[holeNumber]![i].toString()
            : 'N/A';
        scoreDetails.add('$playerName: $playerScore');
      }
      scoreText += '  ${scoreDetails.join('  ')}';
    } else {
      scoreText = '  Tap to add scores';
    }

    return ListTile(
      title: Text('Hole $holeNumber'),
      subtitle: Text(scoreText),
      onTap: () => _showHoleDetailsDialog(holeNumber),
    );
  }

  void _showPlayerRankings(BuildContext context) {
    // Calculate total scores for each player
    Map<String, int> totalScores = {};
    for (var name in playerNames) {
      int totalScore = 0;
      scores.forEach((hole, playerScores) {
        int playerIndex = playerNames.indexOf(name);
        if (playerScores.length > playerIndex) {
          totalScore += playerScores[playerIndex];
        }
      });
      totalScores[name] = totalScore;
    }

    // Remove players with a total score of 0
    totalScores.removeWhere((name, score) => score == 0);

    // Sort players by total score
    var sortedScores = totalScores.entries.toList()
      ..sort((a, b) => a.value.compareTo(b.value));

    // Create a list of player names and scores for display, sorted by score
    List<Widget> scoreWidgets = sortedScores.map((entry) {
      return Text('${entry.key}: ${entry.value}');
    }).toList();

    // Show the rankings in a dialog
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: const Text('Player Rankings'),
          content: SingleChildScrollView(
            child: ListBody(children: scoreWidgets),
          ),
          actions: <Widget>[
            TextButton(
              child: const Text('OK'),
              onPressed: () => Navigator.of(context).pop(),
            ),
          ],
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Mini Golf Score Keeper'),
        actions: [
          IconButton(
            icon: const Icon(Icons.save),
            onPressed: _saveGame,
            tooltip: 'Save Game',
          ),
          IconButton(
            icon: const Icon(Icons.delete),
            onPressed: () => _confirmDeleteGame(context),
            tooltip: 'Delete Game',
          ),
        ],
      ),
      body: ListView.builder(
        itemCount: _numberOfHoles,
        itemBuilder: (context, index) {
          int holeNumber = index + 1;
          return _buildHoleDetails(holeNumber);
        },
      ),
      floatingActionButton: Align(
        alignment: Alignment.bottomRight,
        child: Padding(
          padding: const EdgeInsets.only(bottom: 16.0),
          // Adjust padding as needed
          child: Column(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              FloatingActionButton(
                heroTag: "deleteHole",
                onPressed: _deleteLastHole,
                tooltip: 'Delete Last Hole',
                backgroundColor: Colors.red,
                child: const Icon(
                    Icons.remove), // Optional: different color for delete
              ),
              const SizedBox(height: 16), // Space between the buttons
              FloatingActionButton(
                heroTag: "addHole",
                onPressed: () {
                  setState(() {
                    _numberOfHoles++; // Increment the number of holes
                    // Initialize par and scores for the new hole with defaults
                    pars[_numberOfHoles] = 0; // Assuming 0 as default par
                    scores[_numberOfHoles] = List.filled(playerNames.length, 0); // Initialize scores with 0
                  });
                },
                tooltip: 'Add New Hole',
                backgroundColor: Colors.green,
                child: const Icon(Icons.add),
              ),
            ],
          ),
        ),
      ),
      bottomNavigationBar: Container(
        color: Colors.blueGrey[100],
        height: 60.0,
        child: SingleChildScrollView(
          scrollDirection: Axis.horizontal,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              // Total Par Display
              GestureDetector(
                onTap: () => _showPlayerRankings(context),
                child: Container(
                  padding: const EdgeInsets.all(10),
                  color: Colors.blueGrey[100],
                  child: Text(
                    'Total Par: ${pars.values.fold(0, (prev, par) => prev + par)}',
                    style: const TextStyle(fontSize: 16),
                  ),
                ),
              ),

              // Divider between Total Par and Players' Scores
              const VerticalDivider(color: Colors.black),
              // Players' Scores
              ...playerNames.map((name) {
                // Calculate total score for each player
                int totalScore =
                scores.values.fold(0, (previousValue, holeScores) {
                  final index = playerNames.indexOf(name);
                  return previousValue +
                      (holeScores.length > index ? holeScores[index] : 0);
                });
                return Padding(
                  padding: const EdgeInsets.symmetric(horizontal: 8.0),
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: <Widget>[
                      Text(name),
                      Text('Score: $totalScore'),
                    ],
                  ),
                );
              }),
              // Add an IconButton for editing player names
              IconButton(
                icon: const Icon(Icons.edit),
                onPressed: () {
                  _editPlayerNames();
                },
                tooltip: 'Edit Player Names',
              ),
            ],
          ),
        ),
      ),
    );
  }
}