using System;
using System.Collections.Generic;

namespace KYFramework
{
    [ObjectSystem]
    public class ConfigComponentAwakeSystem : AwakeSystem<ConfigComponent>
    {
        public override void Awake(ConfigComponent self)
        {
            self.Load();
        }
    }

    public static class ConfigComponentSystem
    {
        public static void Load(this ConfigComponent self)
        {
            self.allConfig.Clear();

            List<Type> types = Game.EventSystem.GetTypes(typeof(ConfigAttribute));
            foreach (Type type in types)
            {
                object[] attrs = type.GetCustomAttributes(typeof(ConfigAttribute), false);
                
                if(attrs.Length == 0) continue;

                object obj = Activator.CreateInstance(type);
                ACategory icategory = obj as ACategory;
                if (icategory == null)
                {
                    throw new Exception($"class: {type.Name} not inherit from ACategory");
                }
                
                icategory.BeginInit();
                icategory.EndInit();

                self.allConfig[icategory.Config] = icategory;
            }
        }

        public static IConfig GetOne(this ConfigComponent self, Type type)
        {
            ACategory configCategory;
            if (!self.allConfig.TryGetValue(type, out configCategory))
            {
                throw new Exception($"ConfigComponent not found key: {type.FullName}");
            }
            return configCategory.GetOne();
        }

        public static IConfig Get(this ConfigComponent self, Type type, int id)
        {
            ACategory configCategory;
            if (!self.allConfig.TryGetValue(type, out configCategory))
            {
                throw new Exception($"ConfigComponent not found key: {type.FullName}");
            }

            return configCategory.TryGet(id);
        }

        public static IConfig TryGet(this ConfigComponent self, Type type, int id)
        {
            ACategory configCategory;
            if (!self.allConfig.TryGetValue(type, out configCategory))
            {
                return null;
            }
            return configCategory.TryGet(id);
        }
        
        public static IConfig[] GetAll(this ConfigComponent self, Type type)
        {
            ACategory configCategory;
            if (!self.allConfig.TryGetValue(type, out configCategory))
            {
                throw new Exception($"ConfigComponent not found key: {type.FullName}");
            }
            return configCategory.GetAll();
        }

        public static ACategory GetCategory(this ConfigComponent self, Type type)
        {
            ACategory configCategory;
            bool ret = self.allConfig.TryGetValue(type, out configCategory);
            return ret ? configCategory : null;
        }
    }
}