﻿using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Reflection;

namespace Naxis.Core.TypeProvider
{
    public class DefaultTypeNameProvider : ITypeNameProvider, IAssemblyInitializer
    {
        private readonly ConcurrentDictionary<string, Type> _dict = new ConcurrentDictionary<string, Type>();
        private Assembly[] _asemblies;

        public string GetTypeName(Type type)
        {
            return type.FullName;
        }

        public Type GetType(string typeName)
        {
            Type type1;
            if (_dict.TryGetValue(typeName, out type1))
                return type1;
            foreach (var type2 in _asemblies.Select(assembly => assembly.GetType(typeName)).Where(type2 => type2 != null))
            {
                _dict.TryAdd(typeName, type2);
                return type2;
            }
            return null;
        }

        public void Initialize(params Assembly[] assemblies)
        {
            _asemblies = assemblies;
        }
    }
}
