using System.Collections.Generic;
using UnityEngine;

namespace Cryville.Crtr.Config.UI {
	public class PropertyMasterPanel : MonoBehaviour {
		[SerializeField]
		GameObject m_categoryPrefab;

		[SerializeField]
		Transform m_container;

		bool _invalidated = true;

		public void Invalidate() {
			_invalidated = true;
		}

		private IPropertyMasterAdapter m_adapter;
		public IPropertyMasterAdapter Adapter {
			get { return m_adapter; }
			set {
				m_adapter = value;
				Invalidate();
			}
		}

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

		readonly Dictionary<string, List<IPropertyAdapter>> _categories = new Dictionary<string, List<IPropertyAdapter>>();
		public void LoadProperties() {
			_categories.Clear();
			_invalidated = false;
			if (Adapter == null) return;
			foreach (var p in Adapter.GetProperties()) {
				string category = p.Category;
				if (category == null) category = Adapter.DefaultCategory;
				if (!_categories.ContainsKey(category))
					_categories.Add(category, new List<IPropertyAdapter>());
				_categories[category].Add(p);
			}
		}
	}
}
