using System;
using System.IO;
using UnityEngine;
namespace ShiroginSDK.Runtime.Modules.Data.Scripts
{
///
/// ShiroginSDK'nin tüm veri sınıflarının türediği temel sınıf.
/// JSON tabanlı kaydetme, yükleme ve silme işlemlerini sağlar.
///
[Serializable]
public abstract class BaseData
{
///
/// Verinin ilk kez oluşturulup oluşturulmadığını belirtir.
///
[NonSerialized]
public bool IsInitialized;
///
/// Her alt sınıf kendi benzersiz kaydetme anahtarını tanımlar.
/// Örnek: "player_data", "settings_data", "store_data"
///
protected abstract string PrefsKey { get; }
///
/// Verilerin kaydedileceği JSON dosya yolu.
///
protected virtual string FilePath => Path.Combine(Application.persistentDataPath, $"{PrefsKey}.json");
///
/// Veriyi kaydeder.
/// Eğer parametre true ise dosya oluşturur (JSON).
/// Eğer parametre false (varsayılan) ise PlayerPrefs'e kaydeder.
///
public virtual void Save(bool saveToFile = false)
{
try
{
var json = JsonUtility.ToJson(this, false);
if (saveToFile)
{
// Dosya olarak kaydet
File.WriteAllText(FilePath, json);
Debug.Log($"[Data] Saved to FILE → {PrefsKey} ({FilePath})");
}
else
{
// PlayerPrefs olarak kaydet
PlayerPrefs.SetString(PrefsKey, json);
PlayerPrefs.Save();
Debug.Log($"[Data] Saved to PREFS → {PrefsKey}");
}
}
catch (Exception e)
{
Debug.LogError($"[Data] Save failed for {PrefsKey}: {e.Message}");
}
}
///
/// Veriyi yükler; dosya yoksa veya PlayerPrefs’te varsa uygun yerden çeker.
///
public virtual void Load()
{
try
{
if (File.Exists(FilePath))
{
var json = File.ReadAllText(FilePath);
JsonUtility.FromJsonOverwrite(json, this);
Debug.Log($"[Data] Loaded from FILE → {PrefsKey}");
}
else if (PlayerPrefs.HasKey(PrefsKey))
{
var json = PlayerPrefs.GetString(PrefsKey);
JsonUtility.FromJsonOverwrite(json, this);
Debug.Log($"[Data] Loaded from PREFS → {PrefsKey}");
}
else
{
Debug.LogWarning($"[Data] No saved data found for {PrefsKey}. Creating new file.");
IsInitialized = true;
Save(); // Default kaydet (PlayerPrefs’e)
}
}
catch (Exception e)
{
Debug.LogError($"[Data] Load failed for {PrefsKey}: {e.Message}");
}
}
///
/// Veriyi tamamen siler (dosya + PlayerPrefs).
///
public virtual void Delete()
{
try
{
if (File.Exists(FilePath))
File.Delete(FilePath);
if (PlayerPrefs.HasKey(PrefsKey))
PlayerPrefs.DeleteKey(PrefsKey);
Debug.Log($"[Data] Deleted → {PrefsKey}");
}
catch (Exception e)
{
Debug.LogError($"[Data] Delete failed for {PrefsKey}: {e.Message}");
}
}
///
/// Verinin var olup olmadığını kontrol eder.
///
public bool Exists()
{
return File.Exists(FilePath) || PlayerPrefs.HasKey(PrefsKey);
}
///
/// Dosya içeriğini JSON string olarak döndürür (debug amaçlı).
///
public string ToJson(bool prettyPrint = true)
{
return JsonUtility.ToJson(this, prettyPrint);
}
}
}