using System;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
using UnityEngine;
using WS;

[CustomEditor(typeof(WSComponentView))]
public class ComponentViewEditor : Editor
{
    public override void OnInspectorGUI()
    {
        WSComponentView componentView = (WSComponentView)target;
        object component = componentView.Component;
        //if (component.GetType() == typeof (ILTypeInstance))
        //{
        //    return;
        //}
        ComponentViewHelper.Draw(component);
    }

    private void OnDestroy()
    {
        ComponentViewHelper.TypeDrawerDestroy();
    }
}

public static class ComponentViewHelper
{
    private static readonly List<ITypeDrawer> typeDrawers = new List<ITypeDrawer>();

    ///<summary>初始化</summary>
    static ComponentViewHelper()
    {
        Assembly assembly = typeof(ComponentViewHelper).Assembly;
        foreach (Type type in assembly.GetTypes())
        {
            if (!type.IsDefined(typeof(TypeDrawerAttribute)))
            {
                continue;
            }
            ITypeDrawer iTypeDrawer = (ITypeDrawer)Activator.CreateInstance(type);
            typeDrawers.Add(iTypeDrawer);
        }
    }

    ///<summary>销毁数据</summary>
    public static void TypeDrawerDestroy()
    {
        for (int i = 0; i < typeDrawers.Count; i++)
        {
            typeDrawers[i].Destroy();
        }
    }

    ///<summary>绘制窗口</summary>
    public static void Draw(object obj)
    {
        FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy);
        EditorGUILayout.BeginVertical();

        foreach (FieldInfo fieldInfo in fields)
        {
            Type type = fieldInfo.FieldType;
            if (type.IsDefined(typeof(HideInInspector), false))
            {
                continue;
            }

            if (fieldInfo.IsDefined(typeof(HideInInspector), false))
            {
                continue;
            }

            object value = fieldInfo.GetValue(obj);
            foreach (ITypeDrawer typeDrawer in typeDrawers)
            {
                if (!typeDrawer.HandlesType(type, value))
                {
                    continue;
                }

                string fieldName = fieldInfo.Name;
                if (fieldName.Length > 17 && fieldName.Contains("k__BackingField"))
                {
                    fieldName = fieldName.Substring(1, fieldName.Length - 17);
                }
                value = typeDrawer.DrawAndGetNewValue(type, fieldName, value, null);
                fieldInfo.SetValue(obj, value);
                break;
            }
        }
        EditorGUILayout.EndVertical();
    }
}