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

[TypeDrawer]
public class ListTypeDrawer : ITypeDrawer
{
    private Dictionary<object, bool> dictoggle = new Dictionary<object, bool>();

    public bool HandlesType(Type type, object value)
    {
        IList list = value as IList;
        return list != null;
    }

    public object DrawAndGetNewValue(Type memberType, string memberName, object value, object target)
    {
        IList list = (IList)value;
        SetDicToggle(list);

        dictoggle[list] = EditorGUILayout.Foldout(dictoggle[list], memberName);
        if (dictoggle[list])
        {
            EditorGUILayout.BeginHorizontal();
            GUILayout.Label("", GUILayout.Width(10));
            GUILayout.Label($"Count {list.Count}");
            EditorGUILayout.EndHorizontal();
            for (int i = 0; i < list.Count; i++)
            {
                if (list[i] != null)
                {
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Label("", GUILayout.Width(10));
                    dictoggle[list[i]] = EditorGUILayout.Foldout(dictoggle[list[i]], $"{memberName} {i}【{list[i].GetType().Name}】");
                    EditorGUILayout.EndHorizontal();
                    if (dictoggle[list[i]])
                        ComponentViewHelper.Draw(list[i]);
                }
                else
                {
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Label("", GUILayout.Width(10));
                    GUILayout.Label($"{memberName} {i} Null");
                    EditorGUILayout.EndHorizontal();
                }
            }
        }
        return list;
    }

    private void SetDicToggle(IList list)
    {
        if (!dictoggle.ContainsKey(list))
        {
            dictoggle[list] = false;
        }
        for (int i = 0; i < list.Count; i++)
        {
            if (list[i] != null)
            {
                if (!dictoggle.ContainsKey(list[i]))
                    dictoggle[list[i]] = false;
            }
        }
    }

    public void Destroy()
    {
        dictoggle.Clear();
    }
}