using Sirenix.OdinInspector;
using UnityEngine;
using UnityEngine.Serialization;

namespace Sets
{
	public abstract class AssetsSet<T> : BaseSet<T> where T : ScriptableObject
	{
		[FormerlySerializedAs("doNotLoopUpAutomatically")] [SerializeField] protected bool doNotLookUpAutomatically;
		
#if UNITY_EDITOR
		private void OnValidate()
		{
			if (!doNotLookUpAutomatically)
			{
				Cleanup();
				LookUp();
			}	
		}
#endif
	
		[PropertyOrder(8)]
		[Button]
		protected virtual void LookUp()
		{
#if UNITY_EDITOR
			var guids = UnityEditor.AssetDatabase.FindAssets("*");
			for (int i = 0; i < guids.Length; i++)
			{
				var path = UnityEditor.AssetDatabase.GUIDToAssetPath(guids[i]);
				var asset = UnityEditor.AssetDatabase.LoadAssetAtPath<ScriptableObject>(path);
				if(asset != null && asset is T)
					Add(asset as T);
			}
#endif
		}

		[PropertyOrder(9)]
		[Button]
		protected virtual void Cleanup()
		{
#if UNITY_EDITOR
			for (int i = items.Count - 1; i >= 0; i--)
			{
				if(items[i] == null)
					items.RemoveAt(i);
			}
#endif
		}

	}
}