using System;
using System.Collections.Generic;
using System.Reflection;

namespace Quadarax.Foundation.Core.Reflection
{
    public static class TypeUtils
    {

        #region *** Private Fields ***
        private static readonly IDictionary<string, Type?> m_oRemTypeCache = new Dictionary<string, Type?>();
        // ReSharper disable InconsistentNaming
        private static readonly object @lock;
        // ReSharper restore InconsistentNaming
        #endregion
        #region *** Public Properties ***
        #endregion
        #region *** Constructors ***
        static TypeUtils()
        {
            @lock = new object();
        }
        #endregion
        #region *** Public operations & overrides ***
        public static Type? GetRemoteType(string sReflectionQualifiedName)
        {
            if (m_oRemTypeCache.TryGetValue(sReflectionQualifiedName, out var type))
                lock (@lock)
                {
                    return type;
                }

            var oName = new QualifiedName(sReflectionQualifiedName);
            Type? oType;
            if (oName.Assembly == null)
            {
                oType = Type.GetType(oName.Name, true);
            }
            else
            {
                var oAssembly = Assembly.Load(oName.Assembly);
                oType = oAssembly.GetType(oName.Name, true);
            }
            lock (@lock)
            {
                m_oRemTypeCache.Add(sReflectionQualifiedName, oType);
            }
            return oType;
        }
        #endregion
        #region *** Private operations & overrides ***
        #endregion               
    }
}
