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

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

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

    public object DrawAndGetNewValue(Type memberType, string memberName, object value, object target)
    {
        IDictionary dic = value as IDictionary;
        SetDicToggle(dic);

        dictoggle[dic] = EditorGUILayout.Foldout(dictoggle[dic], memberName);
        if (dictoggle[dic])
        {
            if (dic.Keys.Count > 0)
            {
                EditorGUILayout.BeginHorizontal();
                GUILayout.Label("", GUILayout.Width(10));
                GUILayout.Label($"Count {dic.Keys.Count}");
                EditorGUILayout.EndHorizontal();
                object[] array = new object[dic.Keys.Count];
                dic.Keys.CopyTo(array, 0);
                for (int i = 0; i < array.Length; i++)
                {
                    EditorGUILayout.BeginHorizontal();
                    GUILayout.Label("", GUILayout.Width(10));
                    dictoggle[array[i]] = EditorGUILayout.Foldout(dictoggle[array[i]], $"{memberName} {i}【{array[i].GetType().Name}】");
                    EditorGUILayout.EndHorizontal();
                    if (dictoggle[array[i]])
                        ComponentViewHelper.Draw(dic[array[i]]);
                }
            }
        }
        return value;
    }

    private void SetDicToggle(IDictionary dic)
    {
        if (!dictoggle.ContainsKey(dic))
        {
            dictoggle[dic] = false;
        }

        object[] array = new object[dic.Keys.Count];
        dic.Keys.CopyTo(array, 0);
        for (int i = 0; i < array.Length; i++)
        {
            if (array[i] != null)
            {
                if (!dictoggle.ContainsKey(array[i]))
                    dictoggle[array[i]] = false;
            }

            if (dic[array[i]] != null)
            {
                if (!dictoggle.ContainsKey(dic[array[i]]))
                    dictoggle[dic[array[i]]] = false;
            }
        }
    }

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