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

namespace XGame.Framework.ObjectCollection
{
    [Serializable]
    public class ObjectCollector : IObjectCollector
    {
#if UNITY_EDITOR
        public Type collectorType = typeof(GameObject);
        public Type[] blackTypes = null;
        /// <summary>
        /// 绑定的脚本类型，生成代码用
        /// </summary>
        [SerializeField]
        public List<string> bindTypes = new List<string>();
#endif

        [SerializeField]
        public List<string> keys = new List<string>();

        [SerializeField]
        public List<UnityEngine.Object> values = new List<UnityEngine.Object>();

        private Dictionary<string, UnityEngine.Object> _objectsMap;
        private bool _isInited = false;

        public UnityEngine.Object this[string key]
        {
            get
            {
                if (!_isInited) CacheDict();
                if (_objectsMap.TryGetValue(key, out UnityEngine.Object value))
                    return value;
                Log.Debug($"Can't find the key: {key}, Please Check it");
                return null;
            }
        }

        public List<string> Keys => keys;

        public List<UnityEngine.Object> Objects => values;

        public T GetComponent<T>(string key) where T : Component
        {
            var obj = this[key];
            if (obj is GameObject go)
            {
                return go.GetComponent<T>();
            }
            if (obj is Component component)
            {
                return component.gameObject.GetComponent<T>();
            }
            //Log.Debug($"Can't find Component. key: {key} Type:{typeof(T)}");
            return null;
        }

        public GameObject GetGameObject(string key)
        {
            var obj = this[key];
            if (obj is GameObject go)
            {
                return go;
            }
            if (obj is Component component)
            {
                return component.gameObject;
            }
            Log.Error($"Can't find GameObject. key: {key}");
            return null;
        }

        private void CacheDict()
        {
            _isInited = true;

            _objectsMap = new Dictionary<string, UnityEngine.Object>(keys.Count);
            for (int i = 0, length = keys.Count; i < length; i++)
            {
                _objectsMap[keys[i]] = values[i];
            }
        }
    }
}
