| | 1 | | using System; |
| | 2 | | using DCL.Helpers; |
| | 3 | | using UnityEngine; |
| | 4 | |
|
| | 5 | | namespace DCL.SettingsCommon |
| | 6 | | { |
| | 7 | | public class SettingsModule<T> : ISettingsRepository<T> where T : struct |
| | 8 | | { |
| | 9 | | public event Action<T> OnChanged; |
| | 10 | |
|
| | 11 | | private readonly string playerPrefsKey; |
| | 12 | | private readonly T defaultPreset; |
| | 13 | |
|
| 0 | 14 | | public T Data => dataValue; |
| | 15 | | private T dataValue; |
| | 16 | |
|
| 1920 | 17 | | public SettingsModule(string playerPrefsKey, T defaultPreset) |
| | 18 | | { |
| 1920 | 19 | | this.playerPrefsKey = playerPrefsKey; |
| 1920 | 20 | | this.defaultPreset = defaultPreset; |
| 1920 | 21 | | Preload(); |
| 1920 | 22 | | } |
| | 23 | |
|
| | 24 | | private void Preload() |
| | 25 | | { |
| 1920 | 26 | | dataValue = defaultPreset; |
| 1920 | 27 | | if (!PlayerPrefsUtils.HasKey(playerPrefsKey)) |
| 1920 | 28 | | return; |
| | 29 | |
|
| | 30 | | try |
| | 31 | | { |
| 0 | 32 | | dataValue = JsonUtility.FromJson<T>(PlayerPrefsUtils.GetString(playerPrefsKey)); |
| 0 | 33 | | } |
| | 34 | | catch (Exception e) |
| | 35 | | { |
| 0 | 36 | | Debug.LogError(e.Message); |
| 0 | 37 | | } |
| 0 | 38 | | } |
| | 39 | |
|
| 0 | 40 | | public void Reset() { Apply(defaultPreset); } |
| | 41 | |
|
| | 42 | | public void Apply(T newSettings) |
| | 43 | | { |
| 0 | 44 | | if (dataValue.Equals(newSettings)) |
| 0 | 45 | | return; |
| | 46 | |
|
| 0 | 47 | | dataValue = newSettings; |
| 0 | 48 | | OnChanged?.Invoke(dataValue); |
| 0 | 49 | | } |
| | 50 | |
|
| 0 | 51 | | public void Save() { PlayerPrefsUtils.SetString(playerPrefsKey, JsonUtility.ToJson(dataValue)); } |
| | 52 | |
|
| 308 | 53 | | public bool HasAnyData() => !Data.Equals(defaultPreset); |
| | 54 | | } |
| | 55 | | } |