using Cryville.Crtr.Browsing;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using UnityEngine;

namespace Cryville.Crtr {
	public class SettingsPanel : MonoBehaviour {
		[SerializeField]
		GameObject m_categoryPrefab;

		[SerializeField]
		Transform m_container;

		bool _invalidated = true;
		object m_target;
		public object Target {
			get {
				return m_target;
			}
			set {
				if (m_target != value) {
					m_target = value;
					_invalidated = true;
				}
			}
		}

		public void Update() {
			if (!_invalidated) return;
			LoadProperties();
			foreach (Transform c in m_container) GameObject.Destroy(c.gameObject);
			foreach (var c in _categories) {
				var obj = GameObject.Instantiate<GameObject>(m_categoryPrefab, m_container, false);
				obj.GetComponent<PropertyCategoryPanel>().Load(c.Key, c.Value, Target);
			}
		}

		Dictionary<string, List<PropertyInfo>> _categories = new Dictionary<string, List<PropertyInfo>>();
		public void LoadProperties() {
			_categories.Clear();
			_invalidated = false;
			if (Target == null) return;
			foreach (var p in Target.GetType().GetProperties()) {
				bool browsable = true;
				string category = "miscellaneous";
				foreach (var attr in p.GetCustomAttributes(true)) {
					if (attr is BrowsableAttribute) {
						browsable = ((BrowsableAttribute)attr).Browsable;
						if (!browsable) break;
					}
					else if (attr is CategoryAttribute) {
						category = ((CategoryAttribute)attr).Category;
					}
				}
				if (!browsable) continue;
				if (!_categories.ContainsKey(category))
					_categories.Add(category, new List<PropertyInfo>());
				_categories[category].Add(p);
			}
		}
	}
}