-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgressManager.cs
More file actions
399 lines (336 loc) · 14.5 KB
/
ProgressManager.cs
File metadata and controls
399 lines (336 loc) · 14.5 KB
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using TMPro;
using UnityEngine;
using UnityEngine.Networking;
[System.Serializable]
public class ProgressData
{
public int lastCompletedClueIndex = -1; // Last successfully collected treasure (0-based, -1 means none)
public int[] collectedTreasures; // Array of collected clue indices
public int totalTreasuresCollected = 0; // Count for validation
public int nextClueIndex = 0; // Next clue to hunt (0-based)
public int teamAssignedClueIndex = 0; // Original starting clue for this team
public string lastSavedTimestamp; // When progress was last saved
public bool physicalGameActive = false; // True when physical game is pending completion
public int physicalGameClueIndex = -1; // Which clue's physical game is active
public ProgressData()
{
collectedTreasures = new int[0];
lastSavedTimestamp = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
}
}
public class ProgressManager : MonoBehaviour
{
[Header("Firebase Configuration")]
[Tooltip("Base RTDB URL - will be inherited from FirebaseRTDBFetcher if not set")]
public string realtimeDatabaseBaseUrl = "";
[Tooltip("Auth token - will be inherited from FirebaseRTDBFetcher if not set")]
public string authToken = "";
[Header("Settings")]
[Tooltip("Enable debug logging for progress operations")]
public bool debugMode = true;
[Header("Mobile Debug")]
public TMPro.TMP_Text mobileDebugText;
// References to other managers
private FirebaseRTDBFetcher rtdbFetcher;
private TreasureHuntManager treasureHuntManager;
// Current progress data
private ProgressData currentProgress;
private string activeUID;
void Start()
{
// Find references to other managers
rtdbFetcher = FindObjectOfType<FirebaseRTDBFetcher>();
treasureHuntManager = FindObjectOfType<TreasureHuntManager>();
// Inherit Firebase settings from RTDB fetcher if not set
if (rtdbFetcher != null)
{
if (string.IsNullOrEmpty(realtimeDatabaseBaseUrl))
realtimeDatabaseBaseUrl = rtdbFetcher.realtimeDatabaseBaseUrl;
if (string.IsNullOrEmpty(authToken))
authToken = rtdbFetcher.authToken;
}
if (debugMode)
{
Debug.Log("ProgressManager initialized");
if (mobileDebugText != null) mobileDebugText.text = "ProgressManager initialized";
}
}
// Check if a UID has existing progress
public void CheckProgressForUID(string uid, System.Action<bool, ProgressData> callback)
{
if (string.IsNullOrEmpty(uid))
{
callback?.Invoke(false, null);
return;
}
activeUID = uid;
StartCoroutine(LoadProgressFromFirebase(uid, callback));
}
private IEnumerator LoadProgressFromFirebase(string uid, System.Action<bool, ProgressData> callback)
{
string url = BuildProgressUrl(uid);
if (debugMode)
{
Debug.Log($"Loading progress from: {url}");
if (mobileDebugText != null) mobileDebugText.text = $"Loading progress for {uid}...";
}
using (var request = UnityWebRequest.Get(url))
{
request.timeout = 15;
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
string json = request.downloadHandler.text;
if (string.IsNullOrWhiteSpace(json) || json == "null")
{
// No progress data exists - new game
if (debugMode)
{
Debug.Log($"No existing progress found for UID: {uid}");
if (mobileDebugText != null) mobileDebugText.text = "No existing progress - starting new game";
}
callback?.Invoke(false, null);
}
else
{
try
{
ProgressData progressData = JsonUtility.FromJson<ProgressData>(json);
if (IsValidProgressData(progressData))
{
currentProgress = progressData;
if (debugMode)
{
Debug.Log($"Progress loaded: {progressData.totalTreasuresCollected} treasures collected, next clue: {progressData.nextClueIndex}");
if (mobileDebugText != null) mobileDebugText.text = $"Progress loaded: {progressData.totalTreasuresCollected} treasures collected";
}
callback?.Invoke(true, progressData);
}
else
{
// Invalid progress data - treat as new game
Debug.LogWarning($"Invalid progress data for UID: {uid}, starting new game");
if (mobileDebugText != null) mobileDebugText.text = "Invalid progress data - starting new game";
callback?.Invoke(false, null);
}
}
catch (System.Exception e)
{
Debug.LogError($"Failed to parse progress data: {e.Message}");
if (mobileDebugText != null) mobileDebugText.text = "Failed to parse progress - starting new game";
callback?.Invoke(false, null);
}
}
}
else
{
Debug.LogError($"Failed to load progress: {request.error}");
if (mobileDebugText != null) mobileDebugText.text = "Network error loading progress - starting new game";
callback?.Invoke(false, null);
}
}
}
// Save progress after successful treasure collection
public void SaveProgressAfterCollection(int clueIndex, int teamAssignedStartIndex, int totalClues)
{
if (string.IsNullOrEmpty(activeUID))
{
Debug.LogError("Cannot save progress: no active UID");
if (mobileDebugText != null) mobileDebugText.text = "ERROR: Cannot save progress - no active UID";
return;
}
// Initialize progress if it doesn't exist
if (currentProgress == null)
{
currentProgress = new ProgressData();
currentProgress.teamAssignedClueIndex = teamAssignedStartIndex;
}
// Add to collected treasures if not already present
List<int> collectedList = new List<int>(currentProgress.collectedTreasures);
if (!collectedList.Contains(clueIndex))
{
collectedList.Add(clueIndex);
collectedList.Sort(); // Keep sorted for consistency
}
// Update progress data
currentProgress.collectedTreasures = collectedList.ToArray();
currentProgress.totalTreasuresCollected = collectedList.Count;
currentProgress.lastCompletedClueIndex = clueIndex;
currentProgress.nextClueIndex = CalculateNextClueIndex(clueIndex, teamAssignedStartIndex, totalClues);
currentProgress.lastSavedTimestamp = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
StartCoroutine(SaveProgressToFirebase());
}
private int CalculateNextClueIndex(int lastCompletedIndex, int teamStartIndex, int totalClues)
{
// Calculate next clue in the sequence for this team
int nextIndex = (lastCompletedIndex + 1) % totalClues;
// If we've come full circle back to team's starting index and collected all clues, game is complete
if (nextIndex == teamStartIndex && currentProgress != null && currentProgress.totalTreasuresCollected >= totalClues)
{
return -1; // Indicates game complete
}
return nextIndex;
}
private IEnumerator SaveProgressToFirebase()
{
if (currentProgress == null) yield break;
string url = BuildProgressUrl(activeUID);
string json = JsonUtility.ToJson(currentProgress);
if (debugMode)
{
Debug.Log($"Saving progress to Firebase: {json}");
if (mobileDebugText != null) mobileDebugText.text = $"Saving progress: {currentProgress.totalTreasuresCollected} treasures";
}
using (var request = new UnityWebRequest(url, "PUT"))
{
byte[] body = Encoding.UTF8.GetBytes(json);
request.uploadHandler = new UploadHandlerRaw(body);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
request.timeout = 10;
yield return request.SendWebRequest();
if (request.result == UnityWebRequest.Result.Success)
{
if (debugMode)
{
Debug.Log("Progress saved successfully");
if (mobileDebugText != null) mobileDebugText.text = "Progress saved successfully";
}
}
else
{
Debug.LogError($"Failed to save progress: {request.error}");
if (mobileDebugText != null) mobileDebugText.text = $"Failed to save progress: {request.error}";
}
}
}
private string BuildProgressUrl(string uid)
{
string baseUrl = realtimeDatabaseBaseUrl.TrimEnd('/');
string url = $"{baseUrl}/{uid}/Progress_Follow.json";
if (!string.IsNullOrWhiteSpace(authToken))
{
url += $"?auth={authToken}";
}
if (debugMode)
{
Debug.Log($"Progress URL constructed: {url}");
if (mobileDebugText != null) mobileDebugText.text = $"Progress URL: {url}";
}
return url;
}
private bool IsValidProgressData(ProgressData data)
{
if (data == null) return false;
if (data.collectedTreasures == null) return false;
if (data.totalTreasuresCollected < 0) return false;
if (data.totalTreasuresCollected != data.collectedTreasures.Length) return false;
return true;
}
// Public getters for other systems
public ProgressData GetCurrentProgress()
{
return currentProgress;
}
public bool HasProgress()
{
return currentProgress != null && currentProgress.totalTreasuresCollected > 0;
}
public int[] GetCollectedTreasures()
{
return currentProgress?.collectedTreasures ?? new int[0];
}
public int GetNextClueIndex()
{
return currentProgress?.nextClueIndex ?? 0;
}
public bool IsGameComplete()
{
return currentProgress != null && currentProgress.nextClueIndex == -1;
}
// Initialize progress for new game and save to Firebase
public void InitializeNewGameProgress(int teamStartIndex)
{
if (string.IsNullOrEmpty(activeUID))
{
Debug.LogError("Cannot initialize progress: no active UID");
if (mobileDebugText != null) mobileDebugText.text = "ERROR: Cannot initialize progress - no active UID";
return;
}
currentProgress = new ProgressData();
currentProgress.teamAssignedClueIndex = teamStartIndex;
currentProgress.nextClueIndex = teamStartIndex;
// Immediately save the initial progress to Firebase
StartCoroutine(SaveProgressToFirebase());
if (debugMode)
{
Debug.Log($"Initialized new game progress with starting clue index: {teamStartIndex}");
if (mobileDebugText != null) mobileDebugText.text = $"New game initialized at clue {teamStartIndex}";
}
}
// Clear progress (for testing or reset)
public void ClearProgress()
{
currentProgress = null;
activeUID = "";
if (debugMode)
{
Debug.Log("Progress cleared");
if (mobileDebugText != null) mobileDebugText.text = "Progress cleared";
}
}
// Set active UID (called by FirebaseRTDBFetcher when team data is fetched)
public void SetActiveUID(string uid)
{
activeUID = uid;
if (debugMode)
{
Debug.Log($"ProgressManager active UID set to: {uid}");
if (mobileDebugText != null) mobileDebugText.text = $"Progress UID set: {uid}";
}
}
// Activate physical game tracking (called when physical game panel is shown)
public void SetPhysicalGameActive(int clueIndex)
{
if (currentProgress == null) return;
currentProgress.physicalGameActive = true;
currentProgress.physicalGameClueIndex = clueIndex;
currentProgress.lastSavedTimestamp = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
// Save immediately to Firebase
StartCoroutine(SaveProgressToFirebase());
if (debugMode)
{
Debug.Log($"Physical game activated for clue {clueIndex}");
if (mobileDebugText != null) mobileDebugText.text = $"Physical game active: clue {clueIndex}";
}
}
// Clear physical game tracking (called when physical game is completed)
public void ClearPhysicalGameActive()
{
if (currentProgress == null) return;
currentProgress.physicalGameActive = false;
currentProgress.physicalGameClueIndex = -1;
currentProgress.lastSavedTimestamp = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
// Save immediately to Firebase
StartCoroutine(SaveProgressToFirebase());
if (debugMode)
{
Debug.Log("Physical game completed and cleared");
if (mobileDebugText != null) mobileDebugText.text = "Physical game completed";
}
}
// Check if physical game is active
public bool IsPhysicalGameActive()
{
return currentProgress != null && currentProgress.physicalGameActive;
}
// Get active physical game clue index
public int GetPhysicalGameClueIndex()
{
return currentProgress?.physicalGameClueIndex ?? -1;
}
}