using MonoGame.FourEngine.Exceptions;
using MonoGame.FourEngine.Resources;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

namespace MonoGame.FourEngine.Services
{
    public class BasicResourceRegistry : IResourceRegistry
    {
        private Dictionary<string, TypeInfo> _dict;

        public TypeInfo GetType(string type)
        {
            var dict = _dict ?? (_dict = CreateDict());
            if (!dict.ContainsKey(type))
                throw new UnknownResourceTypeException(type);
            return dict[type];
        }

        private Dictionary<string, TypeInfo> CreateDict()
            => ServiceLocator.Types
                .Where(p => typeof(IResource).GetTypeInfo().IsAssignableFrom(p.Value))
                .ToDictionary(p => p.Key, p => p.Value);
    }
}