SenpaiZero

asd

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