using System;
using System.ComponentModel;
using System.Reflection;
using UnityEngine;
using UnityEngine.UI;

namespace Cryville.Common.Unity {
	public class PropertyEditor : MonoBehaviour {

		private object target;
		public object TargetObject {
			get { return target; }
			set {
				target = value;
				ReloadProperties();
			}
		}

		private Text desc;
		private Transform list;
		
		public Action Callback;

		private void ReloadProperties() {
			foreach (Transform p in list) {
				GameObject.Destroy(p.gameObject);
			}
			PropertyInfo[] props = target.GetType().GetProperties();
			foreach (PropertyInfo m in props) {
				var brattr = (BrowsableAttribute[])m.GetCustomAttributes(typeof(BrowsableAttribute), true);
				if (brattr.Length > 0)
					if (brattr[0].Browsable == false)
						continue;
				GameObject mi = GameObject.Instantiate<GameObject>(Resources.Load<GameObject>("Common/PropItem"));
				mi.transform.SetParent(list, false);
				mi.GetComponent<PropItem>().PropertyName = m.Name;
				mi.GetComponent<PropItem>().Target = target;
				mi.GetComponent<PropItem>().editor = this;
			}
		}

#pragma warning disable IDE0051
		void Awake() {
			Transform panel = transform.Find("Panel");
			desc = panel.Find("Description").GetComponent<Text>();
			list = panel.Find("PropList").Find("PropListInner");
			SetDescription("(Property)", "");
		}
#pragma warning restore IDE0051

		public void SetDescription(string n, string d) {
			desc.text = "<b>" + n + "</b>\n" + d;
		}

		public void Close() {
			if (Callback != null) Callback.Invoke();
			GameObject.Destroy(gameObject);
		}
	}
}
