namespace Zinnia.Data.Collection
{
using System;
using UnityEngine;
using UnityEngine.Events;
using Zinnia.Data.Collection.List;
using Zinnia.Extension;
///
/// Holds a collection of key/value relations between GameObjects and allows searching for a given key in the collection to emit the linked value.
///
public class GameObjectRelations : MonoBehaviour
{
///
/// Defines the event for the output .
///
[Serializable]
public class GameObjectUnityEvent : UnityEvent { }
[Tooltip("The collection of relations.")]
[SerializeField]
private GameObjectRelationObservableList relations;
///
/// The collection of relations.
///
public GameObjectRelationObservableList Relations
{
get
{
return relations;
}
set
{
relations = value;
}
}
///
/// Emitted when a value is retrieved for a given key or relation index.
///
public GameObjectUnityEvent ValueRetrieved = new GameObjectUnityEvent();
///
/// Emitted when a no key can be found the given key or relation index.
///
public UnityEvent KeyNotFound = new UnityEvent();
///
/// Attempts to get the value in the list of relations for the given key.
///
/// The key of the relation to get the value for.
/// The value for the given key.
public virtual GameObject GetValue(GameObject key)
{
if (!this.IsValidState())
{
return null;
}
foreach (GameObjectRelationObservableList.Relation relation in Relations.NonSubscribableElements)
{
if (key.Equals(relation.Key))
{
ValueRetrieved?.Invoke(relation.Value);
return relation.Value;
}
}
KeyNotFound?.Invoke();
return null;
}
///
/// Attempts to get the value in the list of relations for the given index.
///
/// The index of the relation to get the value for.
/// The value for the given index.
public virtual GameObject GetValue(int relationIndex)
{
if (!this.IsValidState())
{
return null;
}
for (int index = 0; index < Relations.NonSubscribableElements.Count; index++)
{
if (index == relationIndex)
{
GameObject foundValue = Relations.NonSubscribableElements[index].Value;
ValueRetrieved?.Invoke(foundValue);
return foundValue;
}
}
KeyNotFound?.Invoke();
return null;
}
///
/// Attempts to get the value in the list of relations for the given key.
///
/// The key of the relation to get the value for.
public virtual void DoGetValue(GameObject key)
{
GetValue(key);
}
///
/// Attempts to get the value in the list of relations for the given index.
///
/// The index of the relation to get the value for.
public virtual void DoGetValue(int index)
{
GetValue(index);
}
}
}