using System.Text;
using RebootKit.Engine.Foundation;
using UnityEditor;
using UnityEngine;

namespace RebootKit.Editor.PropertyDrawers {
    [CustomPropertyDrawer(typeof(SerializableGuid))]
    public class SerializableGuidDrawer : PropertyDrawer {
        public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) {
            EditorGUI.BeginProperty(position, label, property);
            EditorGUILayout.TextField(label, BuildGuidString(FindGuidParts(property)));
            EditorGUI.EndProperty();
        }

        public SerializedProperty[] FindGuidParts(SerializedProperty property) {
            SerializedProperty[] res = {
                property.FindPropertyRelative("A"),
                property.FindPropertyRelative("B"),
                property.FindPropertyRelative("C"),
                property.FindPropertyRelative("D")
            };
            return res;
        }

        public string BuildGuidString(SerializedProperty[] parts) {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("{0:X8}", parts[0].uintValue);
            sb.AppendFormat("{0:X8}", parts[1].uintValue);
            sb.AppendFormat("{0:X8}", parts[2].uintValue);
            sb.AppendFormat("{0:X8}", parts[3].uintValue);
            return sb.ToString();
        }
    }
}