using System.Collections.Generic;
using System.Reflection;
using UnityEngine;
using UnityEngine.UI;

namespace Cryville.Crtr.Browsing {
	public class PropertyCategoryPanel : MonoBehaviour {
		[SerializeField]
		private GameObject m_propertyPrefab;

		Text _nameLabel = null;

		string _name;
		public string Name {
			get { return _name; }
			set { _name = value; UpdateName(); }
		}

		bool _collapsed = false;
		public bool Collapsed {
			get { return _collapsed; }
			set { _collapsed = value; UpdateName(); }
		}

#pragma warning disable IDE0051
		void Awake() {
			_nameLabel = transform.Find("Name/__text__").GetComponent<Text>();
			transform.Find("Name").GetComponent<Button>().onClick.AddListener(ToggleCollapsed);
		}
#pragma warning restore IDE0051

		public void Load(string name, IEnumerable<PropertyInfo> props, object target) {
			Name = name.ToUpper();
			foreach (var prop in props) {
				var obj = GameObject.Instantiate<GameObject>(m_propertyPrefab, transform, false);
				obj.GetComponent<PropertyPanel>().Load(prop, target);
			}
		}

		void ToggleCollapsed() {
			Collapsed = !Collapsed;
			for (int i = 1; i < transform.childCount; i++) {
				transform.GetChild(i).gameObject.SetActive(!Collapsed);
			}
		}

		private void UpdateName() {
			_nameLabel.text = (Collapsed ? "+ " : "- ") + Name;
		}
	}
}