using System.Collections.Generic;
using UnityEngine;
using Firebase.Firestore;
using Firebase.Auth;
using Firebase.Extensions;
namespace BulletHellTemplate
{
///
/// Handles saving and loading reward data from Firebase and PlayerPrefs.
/// Prevents multiple calls to Firebase during initialization.
///
public static class RewardSaveManager
{
///
/// Loads rewards from Firestore for a specified collection and invokes a callback with the data.
///
public static void LoadRewards(string collectionName, System.Action> onLoaded)
{
FirebaseUser user = FirebaseAuth.DefaultInstance.CurrentUser;
if (user == null) return;
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
DocumentReference docRef = db.Collection("Players").Document(user.UserId).Collection(collectionName).Document("RewardData");
docRef.GetSnapshotAsync().ContinueWithOnMainThread(task =>
{
if (task.IsCompleted && task.Result.Exists)
{
Dictionary data = task.Result.ToDictionary();
onLoaded?.Invoke(data);
}
else
{
Debug.LogError("Failed to load reward data.");
onLoaded?.Invoke(null);
}
});
}
///
/// Saves rewards to Firestore for a specified collection, and also stores them locally in PlayerPrefs.
///
public static void SaveRewards(string collectionName, Dictionary data)
{
FirebaseUser user = FirebaseAuth.DefaultInstance.CurrentUser;
if (user == null) return;
FirebaseFirestore db = FirebaseFirestore.DefaultInstance;
DocumentReference docRef = db.Collection("Players").Document(user.UserId).Collection(collectionName).Document("RewardData");
docRef.SetAsync(data).ContinueWithOnMainThread(task =>
{
if (task.IsCompleted)
{
Debug.Log($"{collectionName} rewards saved successfully.");
}
else
{
Debug.LogError($"Failed to save {collectionName} rewards: {task.Exception}");
}
});
// Save locally
SaveRewardsLocally(collectionName, data);
}
///
/// Saves rewards data locally in PlayerPrefs as JSON.
///
private static void SaveRewardsLocally(string collectionName, Dictionary data)
{
string json = JsonUtility.ToJson(data);
PlayerPrefs.SetString(collectionName, json);
PlayerPrefs.Save();
}
///
/// Loads rewards data from PlayerPrefs if available.
///
public static Dictionary LoadRewardsLocally(string collectionName)
{
string json = PlayerPrefs.GetString(collectionName, null);
return string.IsNullOrEmpty(json) ? null : JsonUtility.FromJson>(json);
}
}
}