using XGame.Framework.ObjectCollection;
using System;
using System.Linq;
using System.Reflection;
using UnityEditor;

namespace XGame.Editor.ObjectCollection
{
    public partial class ObjectCollectorEditor
    {
        private static BindingFlags flags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;

        /// <summary>
        /// ObjectCollectorDrawer
        /// </summary>
        /// <param name="property">objectCollector</param>
        /// <param name="objectType">持有OC的实例类型</param>
        /// <param name="collectorType">OC收集的类型</param>
        /// <param name="isGenerate">是否绘制生成按钮</param>
        /// <param name="blackTypes">黑名单</param>
        public static void ObjectCollectorDrawer(SerializedProperty property, Type objectType, Type collectorType,
            bool isGenerate, Type[] blackTypes = null)
        {
            var ob = property.serializedObject.targetObject;
            var selfFields = ob.GetType().GetFields(flags);
            var baseFields = ob.GetType().BaseType.GetFields(flags);
            var fields = selfFields.Concat(baseFields).ToArray();
            foreach (var field in fields)
            {
                if (field.FieldType == typeof(ObjectCollector))
                {
                    var objectCollector = field.GetValue(ob) as ObjectCollector;
                    objectCollector.objectType = objectType;
                    objectCollector.collectorType = collectorType;
                    objectCollector.isGenerate = isGenerate;
                    objectCollector.blackTypes = blackTypes;
                    break;
                }
            }
            EditorGUILayout.PropertyField(property);
        }

        public static void ObjectCollectorDrawer(SerializedProperty property, Type collectorType)
        {
            var ob = property.serializedObject.targetObject;
            var selfFields = ob.GetType().GetFields(flags);
            var baseFields = ob.GetType().BaseType.GetFields(flags);
            var fields = selfFields.Concat(baseFields).ToArray();
            foreach (var field in fields)
            {
                if (field.FieldType == typeof(ObjectCollector))
                {
                    var objectCollector = field.GetValue(ob) as ObjectCollector;
                    objectCollector.objectType = typeof(UnityEngine.Object);
                    objectCollector.collectorType = collectorType;
                    objectCollector.isGenerate = false;
                    break;
                }
            }
            EditorGUILayout.PropertyField(property);
        }
    }
}
