using System; using System.Collections.Generic; using System.Linq; using System.Text; using UnityEngine; using Random = UnityEngine.Random; namespace SpellBoundAR.Items { [CreateAssetMenu(menuName = "Scriptable Objects/Gameplay/Item Types Database")] public class Database : ScriptableObject { private static Database _instance; public static Database Instance { get { if (_instance) return _instance; Database[] databases = Resources.LoadAll(string.Empty); if (databases == null || databases.Length == 0) { throw new Exception("Resources: Could not find Item Types Database: "); } if (databases.Length > 1) { Debug.LogWarning("Resources: Multiple instances of Item Types Database: "); } _instance = databases[0]; return _instance; } } [SerializeField] private List types = new(); private Dictionary _dictionary; public List Types => types; public ScriptedItemTypeData GetItemTypeByName(string itemTypeName) { return types.Find(test => test.Name == itemTypeName); } public ScriptedItemTypeData GetItemTypeByID(string itemTypeID) { if (string.IsNullOrWhiteSpace(itemTypeID)) return null; if (_dictionary == null) RebuildDictionary(); return _dictionary.ContainsKey(itemTypeID) ? _dictionary[itemTypeID] : null; } public ScriptedItemTypeData GetRandomItemType() { if (_dictionary == null) RebuildDictionary(); return _dictionary.Count > 0 ? _dictionary.ElementAt(Random.Range(0, _dictionary.Count)).Value : null; } public void SortList() { types.Sort((a, b) => string.Compare(a.Name, b.Name, StringComparison.OrdinalIgnoreCase)); } public void RebuildDictionary() { if (_dictionary != null) _dictionary.Clear(); else _dictionary = new Dictionary(); int failures = 0; foreach (ScriptedItemTypeData type in types) { try { if (!type) throw new Exception("Null Item Type"); if (string.IsNullOrWhiteSpace(type.ID)) throw new Exception("Item Type with empty key: " + type.Name); if (_dictionary.ContainsKey(type.ID)) throw new Exception("Item Types with duplicate keys: " + type.Name + ", " + _dictionary[type.ID].Name); _dictionary.Add(type.ID, type); } catch (Exception exception) { failures++; if (type) Debug.LogError(exception.Message, type); else Debug.LogError(exception.Message); } } Debug.Log("Rebuilt Item Type Database: " + _dictionary.Count + " Successes, " + failures + " Failures"); } public override string ToString() { StringBuilder result = new StringBuilder(); result.Append("\n"); foreach (ScriptedItemTypeData type in types) { result.Append(type.ID); result.Append("\t"); result.Append(type.Name); result.Append("\n"); } result.Append("\n"); return result.ToString(); } } }