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

namespace VCommon.Reflection
{
    public static class AssemblyGitHashLookup
    {
        private const string MetaKey = "GitHash";

        private static readonly LazyHolder<IReadOnlyDictionary<string, IReadOnlyCollection<Assembly>>> Holder = new LazyHolder<IReadOnlyDictionary<string, IReadOnlyCollection<Assembly>>>(CreateDic);

        public static IReadOnlyDictionary<string, IReadOnlyCollection<Assembly>> All => Holder.Instance;

        public static IReadOnlyDictionary<string, IReadOnlyCollection<string>> AllNames => All.ToDictionary(p => p.Key, p => (IReadOnlyCollection<string>)p.Value.Select(a => a.GetName().Name).ToArray());

        private static IReadOnlyDictionary<string, IReadOnlyCollection<Assembly>> CreateDic()
        {
            var dic = AppDomain.CurrentDomain.GetAssemblies().Where(p =>
             {
                 if (false == p.IsDefined(typeof(AssemblyMetadataAttribute))) return false;
                 return p.GetCustomAttributes<AssemblyMetadataAttribute>().Any(attr => attr.Key == MetaKey);
             }).GroupBy(p =>
                  p.GetCustomAttributes<AssemblyMetadataAttribute>()
                   .Where(attr => attr.Key == MetaKey)
                   .Select(attr => attr.Value)
                   .First()
            ).ToDictionary(p => p.Key, p => (IReadOnlyCollection<Assembly>)p.ToArray());

            return dic;
        }
    }
}
