SenpaiZero

Untitled

Oct 20th, 2024
4,051
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 30.08 KB | None | 0 0
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Threading.Tasks;
  6. using Firebase;
  7. using Firebase.Extensions;
  8. using Firebase.Firestore;
  9. using UnityEngine;
  10.  
  11. public class FirestoneManager : MonoBehaviour
  12. {
  13. [SerializeField] private int YugtoLevelCount = 10;
  14. public static FirestoneManager Instance;
  15. FirebaseFirestore db;
  16. private const string COLLECTION = "Students";
  17. private const string INFO = "Informations";
  18. private const string GAME_INFO = "Game Information";
  19. private const string PERSONAL_INFO = "Personal Information";
  20. private const string SCHOOL_INFO = "School Information";
  21.  
  22. void Awake()
  23. {
  24. Instance = this;
  25. }
  26.  
  27. void Start()
  28. {
  29. db = FirebaseFirestore.DefaultInstance;
  30. }
  31.  
  32. public int GetYugtoLevelCount() => YugtoLevelCount;
  33.  
  34. // Method to verify login and return the document name (ID)
  35. public Task<StudentData> VerifyLogin(string inputUsername, string inputPassword)
  36. {
  37. if(db == null) db = FirebaseFirestore.DefaultInstance;
  38.  
  39. CollectionReference studentsRef = db.Collection(COLLECTION);
  40. TaskCompletionSource<StudentData> taskCompletionSource =
  41. new TaskCompletionSource<StudentData>();
  42.  
  43. studentsRef.GetSnapshotAsync().ContinueWithOnMainThread(async task =>
  44. {
  45. if (!task.IsCompleted || task.Result == null) {
  46. Debug.Log("No users found.");
  47. taskCompletionSource.SetResult(null);
  48. return;
  49. }
  50. if(task.IsFaulted) MessagePopup.Instance.ShowMessage("WALANG INTERNET O HINDI MAKA-KONEK SA MGA GURO");
  51.  
  52. foreach (DocumentSnapshot studentDoc in task.Result.Documents)
  53. {
  54. string storedUsername = studentDoc.GetValue<string>("username");
  55. string storedPassword = studentDoc.GetValue<string>("password");
  56. string storedEmail = studentDoc.GetValue<string>("email");
  57.  
  58. if (storedUsername != inputUsername
  59. || storedPassword != inputPassword) continue;
  60. string documentId = studentDoc.Id;
  61.  
  62. // START SCHOOL INFO
  63. string teacher = "";
  64. string section = "";
  65. int year = 0;
  66. try {
  67. Debug.Log("START SCHOOL INFO");
  68. DocumentReference infoRef = studentDoc.Reference
  69. .Collection(INFO).Document(SCHOOL_INFO);
  70. DocumentSnapshot schoolInfoSnapshot = await infoRef.GetSnapshotAsync();
  71.  
  72. if (!schoolInfoSnapshot.Exists)
  73. {
  74. Debug.LogError("MISSING SCHOOL INFO");
  75. taskCompletionSource.SetResult(null);
  76. return;
  77. }
  78.  
  79. section = schoolInfoSnapshot.GetValue<string>("Section");
  80. year = schoolInfoSnapshot.GetValue<int>("Grade");
  81. teacher = schoolInfoSnapshot.GetValue<string>("Teacher");
  82. } catch(Exception ex) {
  83. Debug.LogError("SCHOOL " + ex.Message);
  84. taskCompletionSource.SetResult(null);
  85. }
  86. // END SCHOOL INFO
  87.  
  88.  
  89. // START GAME INFO
  90. int coins = 0, level = 0, forestDay = 0, forestNight = 0, city = 0, farm = 0;
  91. bool isFirstTime = false;
  92. List<StudentData.StudentHighscore.LevelHS> levelHS = new List<StudentData.StudentHighscore.LevelHS>();
  93. string setting = "", upgrade = "", customization = "";
  94. try {
  95. Debug.Log("START GAME INFO");
  96. DocumentReference gameInfoRef = studentDoc.Reference
  97. .Collection(INFO).Document(GAME_INFO);
  98. DocumentSnapshot gameInfoSnapshot = await gameInfoRef.GetSnapshotAsync();
  99.  
  100. if (!gameInfoSnapshot.Exists)
  101. {
  102. Debug.Log("Creating default game info...");
  103.  
  104. Dictionary<string, object> defaultYugtoHighscore = new Dictionary<string, object>()
  105. {
  106. { "Score", 0 },
  107. { "Time", "00:00:00" }
  108. };
  109.  
  110. await gameInfoRef.SetAsync(new Dictionary<string, object>()
  111. {
  112. { "Coins", 0 },
  113. { "Level", 0 },
  114. { "Customization", "0###-1###0###0###-1###-1###0###0###0###0###0###-1###-1###-1###-1###-1###0" },
  115. { "Settings", "1::0::0.5::0.5::0.5::1::0" },
  116. { "Upgrades", "1::0::0::0::0" },
  117. { "First Time", true}
  118. });
  119.  
  120. // Create the Highscore collection
  121. CollectionReference highscoreCollection = gameInfoRef.Collection("Highscore");
  122.  
  123. // For each level, create a document with default values
  124. for (int i = 1; i <= YugtoLevelCount; i++)
  125. {
  126. await highscoreCollection.Document($"Level{i}").SetAsync(defaultYugtoHighscore);
  127. }
  128.  
  129. // Optionally, you can create the Activity document
  130. await highscoreCollection.Document("Activity").SetAsync(new Dictionary<string, object>()
  131. {
  132. { "City", 0 },
  133. { "Farm", 0 },
  134. { "ForestDay", 0 },
  135. { "ForestNight", 0 }
  136. });
  137. }
  138.  
  139. gameInfoSnapshot = await gameInfoRef.GetSnapshotAsync();
  140. coins = gameInfoSnapshot.GetValue<int>("Coins");
  141. level = gameInfoSnapshot.GetValue<int>("Level");
  142. setting = gameInfoSnapshot.GetValue<string>("Settings");
  143. upgrade = gameInfoSnapshot.GetValue<string>("Upgrades");
  144. customization = gameInfoSnapshot.GetValue<string>("Customization");
  145. isFirstTime = gameInfoSnapshot.GetValue<bool>("First Time");
  146.  
  147. CollectionReference highscoreRef = gameInfoRef.Collection("Highscore");
  148. DocumentSnapshot highscoreSnap = await gameInfoRef.GetSnapshotAsync();
  149.  
  150. DocumentReference highscoreActivityRef = highscoreRef.Document("Activity");
  151. DocumentSnapshot highscoreActivitySnap = await highscoreActivityRef.GetSnapshotAsync();
  152.  
  153. DocumentReference highscoreYugtoRef = highscoreRef.Document("Level");
  154. DocumentSnapshot highscoreYugtoSnap = await highscoreYugtoRef.GetSnapshotAsync();
  155.  
  156. forestDay = highscoreActivitySnap.GetValue<int>("ForestDay");
  157. forestNight = highscoreActivitySnap.GetValue<int>("ForestNight");
  158. city = highscoreActivitySnap.GetValue<int>("City");
  159. farm = highscoreActivitySnap.GetValue<int>("Farm");
  160.  
  161. for (int i = 1; i <= YugtoLevelCount; i++)
  162. {
  163. highscoreYugtoRef = highscoreRef.Document("Level"+i);
  164. highscoreYugtoSnap = await highscoreYugtoRef.GetSnapshotAsync();
  165. levelHS.Add(new StudentData.StudentHighscore.LevelHS(
  166. highscoreYugtoSnap.GetValue<int>("Score"),
  167. highscoreYugtoSnap.GetValue<string>("Time")
  168. ));
  169. }
  170. } catch(Exception ex) {
  171. Debug.LogError("GAME " + ex.Message);
  172. taskCompletionSource.SetResult(null);
  173. }
  174. // END OF GAME INFO
  175.  
  176.  
  177. // START PERSONAL INFO
  178. string fullName = "";
  179. try {
  180. Debug.Log("START PERSONAL INFO");
  181. DocumentReference personalInfoRef = studentDoc.Reference
  182. .Collection(INFO).Document(PERSONAL_INFO);
  183. DocumentSnapshot personalInfoSnapshot = await personalInfoRef.GetSnapshotAsync();
  184.  
  185. if (!personalInfoSnapshot.Exists)
  186. {
  187. Debug.LogError($"MISSING PERSONAL INFO: {studentDoc.Id}");
  188. taskCompletionSource.SetResult(null);
  189. return;
  190. }
  191. fullName = personalInfoSnapshot.GetValue<string>("Full Name");
  192. } catch(Exception ex) {
  193. Debug.LogError("PERSONAL " + ex.Message);
  194. taskCompletionSource.SetResult(null);
  195. }
  196. // END OF PERSONAL INFO
  197.  
  198.  
  199.  
  200. // START LEADERBOARD
  201. CollectionReference lbRef = db.Collection("Leaderboard");
  202. DocumentReference lbLvlRef = lbRef.Document("Level");
  203. DocumentSnapshot lbLvlSnap = await lbLvlRef.GetSnapshotAsync();
  204. List<StudentData.DataLeaderboard.Level> levelLB = new List<StudentData.DataLeaderboard.Level>();
  205.  
  206. // START LEVEL
  207. for(int i = 1; i <= YugtoLevelCount; i++) {
  208. lbLvlRef = lbRef.Document($"Level{i} Score");
  209. lbLvlSnap = await lbLvlRef.GetSnapshotAsync();
  210.  
  211. Dictionary<string, object> scoreDict = new Dictionary<string, object>();
  212. Dictionary<string, object> timeDict = new Dictionary<string, object>();
  213.  
  214. foreach (var field in lbLvlSnap.ToDictionary()) {
  215. scoreDict.Add(field.Key, Convert.ToInt32(field.Value));
  216. }
  217.  
  218. lbLvlRef = lbRef.Document($"Level{i} Time");
  219. lbLvlSnap = await lbLvlRef.GetSnapshotAsync();
  220. foreach (var field in lbLvlSnap.ToDictionary()) {
  221. timeDict.Add(field.Key, field.Value.ToString());
  222. }
  223.  
  224. levelLB.Add(new StudentData.DataLeaderboard.Level(
  225. scoreDict, timeDict
  226. ));
  227. }
  228. // END OF LEVEL
  229. // END OF LEADERBOARD
  230.  
  231. // Create the StudentData object with all the fetched data
  232. StudentData studentData = new StudentData(
  233. documentId, storedUsername, storedPassword,
  234. storedEmail, section, year, fullName, level,
  235. new StudentData.StudentSetting(setting),
  236. new StudentData.StudentUpgrade(upgrade),
  237. coins, customization,
  238. new StudentData.StudentHighscore(levelHS, forestDay, forestNight, farm, city),
  239. new StudentData.DataLeaderboard(levelLB,
  240. await GetActivityLB("City"), await GetActivityLB("Farm"),
  241. await GetActivityLB("ForestDay"), await GetActivityLB("ForestNight")),
  242. teacher, isFirstTime
  243. );
  244.  
  245. taskCompletionSource.SetResult(studentData);
  246. Debug.Log("Login successful for user: " + storedUsername);
  247. return;
  248. }
  249. taskCompletionSource.SetResult(null);
  250. });
  251.  
  252. return taskCompletionSource.Task;
  253. }
  254.  
  255. private async Task<StudentData.DataLeaderboard.Activity> GetActivityLB(string stage) {
  256.  
  257. Dictionary<string, object> scoreDict = new Dictionary<string, object>();
  258. Dictionary<string, object> foodDict = new Dictionary<string, object>();
  259. Dictionary<string, object> answerDict = new Dictionary<string, object>();
  260.  
  261. try {
  262. DocumentReference lbActRef = db.Collection("Leaderboard").Document($"{stage} Score");
  263. DocumentSnapshot lbActSnap = await lbActRef.GetSnapshotAsync();
  264. foreach(var field in lbActSnap.ToDictionary())
  265. scoreDict.Add(field.Key, Convert.ToInt32(field.Value));
  266.  
  267. lbActRef = db.Collection("Leaderboard").Document($"{stage} Food");
  268. lbActSnap = await lbActRef.GetSnapshotAsync();
  269. foreach(var field in lbActSnap.ToDictionary())
  270. foodDict.Add(field.Key, Convert.ToInt32(field.Value));
  271.  
  272. lbActRef = db.Collection("Leaderboard").Document($"{stage} Correct Answer");
  273. lbActSnap = await lbActRef.GetSnapshotAsync();
  274. foreach(var field in lbActSnap.ToDictionary())
  275. answerDict.Add(field.Key, Convert.ToInt32(field.Value));
  276. } catch(Exception ex) {
  277. Debug.LogError(ex.Message);
  278. }
  279.  
  280. return new StudentData.DataLeaderboard.Activity(
  281. scoreDict, foodDict, answerDict
  282. );
  283. }
  284. private Task UpdateData(DocumentReference docRef, Dictionary<string, object> data) {
  285. string id = DatabaseData.Instance.student.GetID();
  286. return docRef.UpdateAsync(data).ContinueWithOnMainThread(task =>
  287. {
  288. if(task.IsFaulted) MessagePopup.Instance.ShowMessage("WALANG INTERNET O HINDI MAKA-KONEK SA MGA GURO");
  289. if (task.IsCompleted)
  290. Debug.Log($"Game Highscore yugto updated for student ID: {id}");
  291. else
  292. Debug.LogError($"Failed to update yugto highscore for student ID: {id}: {task.Exception}");
  293. });
  294. }
  295.  
  296. #region GAME FIREBASE
  297. public Task UpdateGameInfo(Dictionary<string, object> data) {
  298. string id = DatabaseData.Instance.student.GetID();
  299. DocumentReference gameRef = db.Collection(COLLECTION)
  300. .Document(id)
  301. .Collection(INFO)
  302. .Document(GAME_INFO);
  303.  
  304. return UpdateData(gameRef, data);
  305. }
  306. public Task UpdateUpgrade(float scoreMult, float speed, int maxFood, int dmg, int time) {
  307. Dictionary<string, object> newData = new Dictionary<string, object>() {
  308. { "Upgrades", StudentData.StudentUpgrade.CombineAllUpgrade(
  309. scoreMult, speed, maxFood, dmg, time
  310. )}
  311. };
  312. return UpdateGameInfo(newData);
  313. }
  314. public Task UpdateSetting(int platform, int mobileControl,
  315. float music, float sfx, float dialogue,
  316. int graphic, int vfx) {
  317. Dictionary<string, object> newData = new Dictionary<string, object>() {
  318. {"Settings", StudentData.StudentSetting
  319. .CombineAllSetting(platform, mobileControl, music,
  320. sfx, dialogue, graphic, vfx)}
  321. };
  322. return UpdateGameInfo(newData);
  323. }
  324.  
  325. public Task UpdateCoins(int coins) {
  326. return UpdateGameInfo(new Dictionary<string, object>() {
  327. { "Coins", coins}
  328. });
  329. }
  330.  
  331. public Task UpdateTutorial() {
  332. return UpdateGameInfo(new Dictionary<string, object>() {
  333. { "First Time", false}
  334. });
  335. }
  336. public Task IncreaseLevel() {
  337. return UpdateGameInfo(new Dictionary<string, object>() {
  338. { "Level", DatabaseData.Instance.student.GetLevel()+1}
  339. });
  340. }
  341. public Task UpdateCharacterCuztomization(string outfit) {
  342. return UpdateGameInfo(new Dictionary<string, object>() {
  343. { "Customization", outfit}
  344. });
  345. }
  346.  
  347. public Task UpdateYugtoHighscore(int level, int score = 0, string time = "") {
  348. string id = DatabaseData.Instance.student.GetID();
  349. DocumentReference gameRef = db.Collection(COLLECTION)
  350. .Document(id)
  351. .Collection(INFO)
  352. .Document(GAME_INFO)
  353. .Collection("Highscore")
  354. .Document("Level"+level);
  355. Dictionary<string, object> data = new Dictionary<string, object>();
  356. if(score != 0) data.Add("Score", score);
  357. if(!string.IsNullOrEmpty(time) || time != "") data.Add("Time", time);
  358.  
  359. return UpdateData(gameRef, data);
  360. }
  361. #endregion
  362.  
  363.  
  364. #region LEADERBOARD
  365. public Task UpdateActivityHighscore(string stage, int score) {
  366. string id = DatabaseData.Instance.student.GetID();
  367. DocumentReference gameRef = db.Collection(COLLECTION)
  368. .Document(id)
  369. .Collection(INFO)
  370. .Document(GAME_INFO)
  371. .Collection("Highscore")
  372. .Document("Activity");
  373. Dictionary<string, object> data = new Dictionary<string, object>() {
  374. { stage, score }
  375. };
  376.  
  377. return UpdateData(gameRef, data);
  378. }
  379.  
  380. public async void CheckLeaderboardExist() {
  381. try
  382. {
  383. CollectionReference lbRef = db.Collection("Leaderboard");
  384. DocumentReference yugtoRef = lbRef.Document("Level");
  385. DocumentSnapshot yugtoSnapshot = await yugtoRef.GetSnapshotAsync();
  386.  
  387. for(int i = 1; i <= YugtoLevelCount; i++) {
  388. // YUGTO SCORE
  389. yugtoRef = lbRef.Document($"Level{i} Score");
  390. yugtoSnapshot = await yugtoRef.GetSnapshotAsync();
  391.  
  392. if(!yugtoSnapshot.Exists) {
  393. await yugtoRef.SetAsync(new Dictionary<string, object>()
  394. {
  395. {"WALA1", 0},
  396. {"WALA2", 0},
  397. {"WALA3", 0},
  398. {"WALA4", 0},
  399. {"WALA5", 0}
  400. });
  401. }
  402.  
  403. // YUGTO TIME
  404. yugtoRef = lbRef.Document($"Level{i} Time");
  405. yugtoSnapshot = await yugtoRef.GetSnapshotAsync();
  406. if(!yugtoSnapshot.Exists) {
  407. await yugtoRef.SetAsync(new Dictionary<string, object>()
  408. {
  409. {"WALA1", "00:00:00"},
  410. {"WALA2", "00:00:00"},
  411. {"WALA3", "00:00:00"},
  412. {"WALA4", "00:00:00"},
  413. {"WALA5", "00:00:00"}
  414. });
  415. }
  416. }
  417.  
  418. await CheckActivityLeaderboard("City");
  419. await CheckActivityLeaderboard("Farm");
  420. await CheckActivityLeaderboard("ForestDay");
  421. await CheckActivityLeaderboard("ForestNight");
  422. } catch(Exception ex) { Debug.LogError(ex.Message); }
  423.  
  424. }
  425.  
  426. public async Task UpdateLeaderboardAct(string stage,
  427. Dictionary<string, int> score = null,
  428. Dictionary<string, int> food = null,
  429. Dictionary<string, int> answer = null) {
  430. CollectionReference lbRef = db.Collection("Leaderboard");
  431.  
  432.  
  433. // SCORE
  434. DocumentReference actRef = lbRef.Document($"{stage} Score");
  435. DocumentSnapshot actSnapshot = await actRef.GetSnapshotAsync();
  436. if(score != null) {
  437. await actRef.SetAsync(score, SetOptions.Overwrite).ContinueWithOnMainThread(
  438. task => {
  439. if (task.IsFaulted) {
  440. MessagePopup.Instance.ShowMessage("WALANG INTERNET O HINDI MAKA-KONEK SA MGA GURO");
  441. Debug.LogError("Error replacing field: " + task.Exception);
  442. }
  443. else Debug.Log("Field replaced successfully.");
  444. }
  445. );
  446. }
  447.  
  448. // FOOD
  449. actRef = lbRef.Document($"{stage} Food");
  450. actSnapshot = await actRef.GetSnapshotAsync();
  451. if(food != null) {
  452. await actRef.SetAsync(food, SetOptions.Overwrite).ContinueWithOnMainThread(
  453. task => {
  454. if (task.IsFaulted) {
  455. MessagePopup.Instance.ShowMessage("WALANG INTERNET O HINDI MAKA-KONEK SA MGA GURO");
  456. Debug.LogError("Error replacing field: " + task.Exception);
  457. }
  458. else Debug.Log("Field replaced successfully.");
  459. }
  460. );
  461. }
  462.  
  463. // CORRECT ANSWER
  464. actRef = lbRef.Document($"{stage} Correct Answer");
  465. actSnapshot = await actRef.GetSnapshotAsync();
  466. if(answer != null) {
  467. await actRef.SetAsync(answer, SetOptions.Overwrite).ContinueWithOnMainThread(
  468. task => {
  469. if (task.IsFaulted) {
  470. MessagePopup.Instance.ShowMessage("WALANG INTERNET O HINDI MAKA-KONEK SA MGA GURO");
  471. Debug.LogError("Error replacing field: " + task.Exception);
  472. }
  473. else Debug.Log("Field replaced successfully.");
  474. }
  475. );
  476. }
  477.  
  478. }
  479.  
  480. public async Task UpdateLeaderboardLevel(int level,
  481. Dictionary<string, object> score = null,
  482. Dictionary<string, object> time = null) {
  483. CollectionReference lbRef = db.Collection("Leaderboard");
  484.  
  485. DocumentReference actRef = lbRef.Document($"Level{level} Score");
  486. DocumentSnapshot actSnapshot = await actRef.GetSnapshotAsync();
  487. if(score != null) {
  488. await actRef.SetAsync(score, SetOptions.Overwrite).ContinueWithOnMainThread(
  489. task => {
  490. if (task.IsFaulted) {
  491. MessagePopup.Instance.ShowMessage("WALANG INTERNET O HINDI MAKA-KONEK SA MGA GURO");
  492. Debug.LogError("Error replacing field: " + task.Exception);
  493. }
  494. else Debug.Log("Field replaced successfully.");
  495. }
  496. );
  497. }
  498.  
  499. if(time == null) return;
  500. actRef = lbRef.Document($"Level{level} Time");
  501. actSnapshot = await actRef.GetSnapshotAsync();
  502. await actRef.SetAsync(time, SetOptions.Overwrite).ContinueWithOnMainThread(
  503. task => {
  504. if (task.IsFaulted) {
  505. MessagePopup.Instance.ShowMessage("WALANG INTERNET O HINDI MAKA-KONEK SA MGA GURO");
  506. Debug.LogError("Error replacing field: " + task.Exception);
  507. }
  508. else Debug.Log("Field replaced successfully.");
  509. }
  510. );
  511. }
  512.  
  513. private async Task CheckActivityLeaderboard(string stage) {
  514. CollectionReference lbRef = db.Collection("Leaderboard");
  515.  
  516. DocumentReference actRef = lbRef.Document($"{stage} Score");
  517. DocumentSnapshot actSnapshot = await actRef.GetSnapshotAsync();
  518. if(!actSnapshot.Exists) {
  519. await actRef.SetAsync(new Dictionary<string, object>()
  520. {
  521. {"WALA1", 0},
  522. {"WALA2", 0},
  523. {"WALA3", 0},
  524. {"WALA4", 0},
  525. {"WALA5", 0}
  526. });
  527. }
  528.  
  529. actRef = lbRef.Document($"{stage} Correct Answer");
  530. actSnapshot = await actRef.GetSnapshotAsync();
  531. if(!actSnapshot.Exists) {
  532. await actRef.SetAsync(new Dictionary<string, object>()
  533. {
  534. {"WALA1", 0},
  535. {"WALA2", 0},
  536. {"WALA3", 0},
  537. {"WALA4", 0},
  538. {"WALA5", 0}
  539. });
  540. }
  541.  
  542. actRef = lbRef.Document($"{stage} Food");
  543. actSnapshot = await actRef.GetSnapshotAsync();
  544. if(!actSnapshot.Exists) {
  545. await actRef.SetAsync(new Dictionary<string, object>()
  546. {
  547. {"WALA1", 0},
  548. {"WALA2", 0},
  549. {"WALA3", 0},
  550. {"WALA4", 0},
  551. {"WALA5", 0}
  552. });
  553. }
  554. }
  555.  
  556. #endregion
  557.  
  558. #region Activities/TODO
  559.  
  560. public async Task<TodoData> GetTodo(string teacherName, string section, string studentName)
  561. {
  562. if (db == null) db = FirebaseFirestore.DefaultInstance;
  563.  
  564. CollectionReference todoRef = db.Collection("Activities").Document(teacherName).Collection(section);
  565.  
  566. TaskCompletionSource<TodoData> taskCompletionSource = new TaskCompletionSource<TodoData>();
  567.  
  568. // Fetch the list of todos for the section
  569. QuerySnapshot todoSnapshot = await todoRef.GetSnapshotAsync();
  570. if (todoSnapshot == null || todoSnapshot.Documents.Count() == 0)
  571. {
  572. Debug.Log("No sections found.");
  573. return null;
  574. }
  575.  
  576. List<TodoData.Todo> todos = new List<TodoData.Todo>();
  577.  
  578. int done = 0;
  579. int notDone = 0;
  580. int all = 0;
  581. foreach (DocumentSnapshot todoDoc in todoSnapshot.Documents)
  582. {
  583. if (todoDoc.GetValue<bool>("isClosed")) continue;
  584. if (DateChecker.IsPastDue(todoDoc.GetValue<string>("Due"))) continue;
  585. if (!DateChecker.HasStarted(todoDoc.GetValue<string>("Start"))) continue;
  586.  
  587. // Get Base Values
  588. int maxAttempts = todoDoc.GetValue<int>("MaxAttemps");
  589. string start = todoDoc.GetValue<string>("Start");
  590. string due = todoDoc.GetValue<string>("Due");
  591. string title = todoDoc.GetValue<string>("Title");
  592. string type = todoDoc.GetValue<string>("Type");
  593. int attempted = 0;
  594. int DefaultPoint = 0;
  595.  
  596. DefaultPoint = todoDoc.GetValue<int>("Default Point");
  597. // Fetch the submission data for the student
  598. CollectionReference submissionRef = todoDoc.Reference.Collection("Submissions");
  599. DocumentSnapshot submissionSnap = await submissionRef.Document(studentName).GetSnapshotAsync();
  600.  
  601. all++;
  602. if (submissionSnap.Exists)
  603. {
  604. attempted = submissionSnap.GetValue<int>("Attemps");
  605. if(attempted > 0) done++;
  606. else notDone++;
  607. if (attempted >= maxAttempts) continue;
  608. }
  609.  
  610. // Fetch the questions
  611. CollectionReference questionRef = todoDoc.Reference.Collection("Questions");
  612. QuerySnapshot questionSnapshot = await questionRef.GetSnapshotAsync();
  613. if (questionSnapshot == null || questionSnapshot.Documents.Count() == 0)
  614. {
  615. Debug.Log("No questions found.");
  616. continue;
  617. }
  618.  
  619. List<TodoData.Todo.Questions> questionList = new List<TodoData.Todo.Questions>();
  620. foreach (DocumentSnapshot questionDoc in questionSnapshot.Documents)
  621. {
  622. int CustomPoint = questionDoc.GetValue<int>("Custom Point");
  623. questionList.Add(new TodoData.Todo.Questions(
  624. questionDoc.GetValue<string>("Question"),
  625. questionDoc.GetValue<string>("Answer"),
  626. new List<string> {
  627. questionDoc.GetValue<string>("Wrong 1"),
  628. questionDoc.GetValue<string>("Wrong 2"),
  629. questionDoc.GetValue<string>("Wrong 3")
  630. },
  631. questionDoc.Id, CustomPoint == -1 ? DefaultPoint : CustomPoint
  632. ));
  633. }
  634.  
  635. // Add the todo to the list
  636. todos.Add(new TodoData.Todo(questionList, maxAttempts, attempted, start,
  637. due, title, type, todoDoc.Id, DefaultPoint));
  638. }
  639.  
  640. TodoData todoData = new TodoData(todos, done, notDone, all);
  641. return todoData;
  642. }
  643.  
  644. public async Task SetSubmissions(string todoID, TodoData.Todo todo) {
  645. if (db == null) db = FirebaseFirestore.DefaultInstance;
  646. try {
  647. DatabaseData.StudentData studDB = DatabaseData.Instance.student;
  648.  
  649. List<TodoData.Todo.Questions> questions = todo.Data;
  650.  
  651. DocumentReference todoRef = db.Collection("Activities")
  652. .Document(studDB.GetTeacher())
  653. .Collection(studDB.GetSection())
  654. .Document(todoID)
  655. .Collection("Submissions")
  656. .Document(studDB.GetFullName());
  657.  
  658. int TotalCorrect = 0;
  659. int TotalWrong = 0;
  660. int TotalScore = 0;
  661. for(int i = 0; i < questions.Count; i++) {
  662. TodoData.Todo.Questions question = questions[i];
  663. if(question?.isCorrect == true) {
  664. TotalCorrect++;
  665. TotalScore += question.CustomPoint;
  666. }
  667. else TotalWrong++;
  668.  
  669.  
  670. await todoRef.Collection("Questions").Document(question.QuestioID).SetAsync(new Dictionary<string, object>() {
  671. { "Question", question.Question},
  672. { "Answer", question.Answer},
  673. { "Wrong 1", question.Wrong[0]},
  674. { "Wrong 2", question.Wrong[1]},
  675. { "Wrong 3", question.Wrong[2]},
  676. { "Selected Answer", question.SelectedAnswer},
  677. { "IsCorrect", question.isCorrect}
  678. });
  679. }
  680.  
  681. await todoRef.SetAsync(new Dictionary<string, object>()
  682. {
  683. { "Attemps", todo.Attempted+1 },
  684. { "Total Correct", TotalCorrect },
  685. { "Total Wrong", TotalWrong },
  686. { "Total Score", TotalScore }
  687. });
  688. } catch(Exception ex) { Debug.LogError(ex.Message); }
  689. }
  690.  
  691. #endregion
  692. }
  693.  
Advertisement
Add Comment
Please, Sign In to add comment