using System.Collections.Generic;
using UnityEngine;
namespace Ashwild.Building
{
///
/// Network-safe registry mapping every BuildableData to a stable numeric id and back. Because
/// ScriptableObject references cannot be sent over the network, the build registry syncs ids
/// instead and resolves them through this database. All machines share the same asset (same
/// build → same order → same ids). Lives in a Resources folder so it loads without wiring.
/// Mirrors ItemDatabase. Rebuilt by Tools ▸ Ashwild ▸ Rebuild Buildable Database.
///
[CreateAssetMenu(fileName = "BuildableDatabase", menuName = "Building/Buildable Database")]
public class BuildableDatabase : ScriptableObject
{
#region Serialized Fields
///
/// All buildables, in a fixed order. The network id of a buildable is its index + 1 (0 = none).
///
[SerializeField] private BuildableData[] buildables;
#endregion
#region State
private static BuildableDatabase instance;
private Dictionary idByBuildable;
#endregion
#region Public API
///
/// The shared database, lazily loaded from Resources/BuildableDatabase.
///
public static BuildableDatabase Instance
{
get
{
if (instance == null)
{
instance = Resources.Load("BuildableDatabase");
if (instance == null)
Debug.LogError("[BuildableDatabase] No 'BuildableDatabase' asset found in a Resources folder — run Tools ▸ Ashwild ▸ Rebuild Buildable Database.");
else
instance.BuildLookup();
}
return instance;
}
}
///
/// All registered buildables, in id order.
///
public BuildableData[] Buildables => buildables;
///
/// Returns the network id of a buildable (0 when null or not registered).
///
public ushort GetId(BuildableData buildable)
{
if (buildable == null) return 0;
if (idByBuildable == null) BuildLookup();
return idByBuildable.TryGetValue(buildable, out ushort id) ? id : (ushort)0;
}
///
/// Resolves a network id back to its BuildableData (null when id is 0 or out of range).
///
public BuildableData GetBuildable(ushort id)
{
if (id == 0 || buildables == null || id > buildables.Length) return null;
return buildables[id - 1];
}
#endregion
#region Internal Helpers
///
/// (Re)builds the buildable → id lookup from the serialized array.
///
private void BuildLookup()
{
idByBuildable = new Dictionary();
if (buildables == null) return;
for (int i = 0; i < buildables.Length; i++)
if (buildables[i] != null) idByBuildable[buildables[i]] = (ushort)(i + 1);
}
#endregion
#if UNITY_EDITOR
///
/// Editor-only: replaces the buildable list (used by the rebuild tool).
///
public void EditorSetBuildables(BuildableData[] all)
{
buildables = all;
}
#endif
}
}