using System;
using System.Collections.Generic;
using System.Linq;
using Fort23.UTool;

namespace Fort23.GameData
{
    public abstract class ConfigHolder
    {
        public abstract Type ConfigType { get; }
        public abstract IConfig GetFirst();
        public abstract List<IConfig> GetAll();
        public abstract IConfig TryGet(int type);
        public abstract void SetConfig(List<IConfig> config);

        public virtual void Init()
        {
        }
    }

    /// <summary>
    /// 管理所有的配置
    /// </summary>
    /// <typeparam name="T"></typeparam>
    [Serializable]
    public abstract class ConfigHolder<T> : ConfigHolder where T : IConfig
    {
        public List<T> configList;
        private Dictionary<int, IConfig> _dictionary;

        public override void Init()
        {
            _dictionary = new Dictionary<int, IConfig>();
            foreach (var config in configList)
            {
                _dictionary.Add(config.GetID(), config);
            }
        }

        public override void SetConfig(List<IConfig> config)
        {
            if (configList != null)
            {
                return;
            }

            configList = new List<T>();
            for (int i = 0; i < config.Count; i++)
            {
                configList.Add((T) config[i]);
            }
        }

        public override Type ConfigType
        {
            get { return typeof(T); }
        }

        public override IConfig TryGet(int ID)
        {
            if (ID <= 0)
            {
                LogTool.Log($"在表{typeof(T)}中没有找到ID：{ID}");
                return null;
            }

            IConfig t;
            if (!_dictionary.TryGetValue(ID, out t))
            {

                LogTool.Log($"在表{typeof(T)}中没有找到ID：{ID}————{_dictionary.Count}");
                return null;
            }

            return t;
        }

        public override List<IConfig> GetAll()
        {
            List<IConfig> configs = _dictionary.Values.ToList();
            return configs;
        }


        public override IConfig GetFirst()
        {
            return _dictionary.Values.First();
        }
    }
}