using System;
using System.Collections.Generic;
using System.Linq;
using SGModule.Common.Helper;

namespace SGModule.ConfigLoader {
    public class ConfigDataManager {
        private readonly Dictionary<Type, object> _configData = new();
        private readonly HashSet<string> _usedKeys = new();
        private Dictionary<string, object> _jsonDictionary = new();


        public void SetJsonDictionary(string json) {
            _jsonDictionary = SerializeHelper.ToObject<Dictionary<string, object>>(json);
            _usedKeys.Clear();
        }

        public void AddConfig(Type type, object instance) {
            _configData[type] = instance;
        }

        public void AddConfig(object configModel) {
            var type = configModel.GetType();
            _configData[type] = configModel;
        }

        public T GetConfig<T>() where T : class {
            if (_configData.TryGetValue(typeof(T), out var obj)) {
                return obj as T;
            }

            Log.ConfigLoader.Error($"未找到类型 {typeof(T).FullName} 的配置");
            return null;
        }

        public bool TryGetJsonValue(string key, out object value) {
            if (!_jsonDictionary.TryGetValue(key, out value)) {
                return false;
            }

            _usedKeys.Add(key);
            return true;
        }

        public IEnumerable<string> GetUnusedKeys() {
            return _jsonDictionary.Keys.Except(_usedKeys);
        }

        public IEnumerable<string> GetJsonKeys() {
            return _jsonDictionary.Keys;
        }
    }
}
