using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace CustomAttributes
{
    class Example20
    {
        static void ShowPluginInformation(string pluginFolder)
        {
            var dir = new DirectoryInfo(pluginFolder);
            Type pluginAttributeType = Assembly.ReflectionOnlyLoad(typeof(PluginInformationAttribute).Assembly.FullName).GetType("CustomAttributes.PluginInformationAttribute");
            foreach (var file in dir.GetFiles("*.exe"))
            {
                Assembly pluginAssembly = Assembly.ReflectionOnlyLoadFrom(file.FullName);
                var plugins =
                     from type in pluginAssembly.GetTypes()
                     let info = type.GetCustomAttributesData().SingleOrDefault(
                                    attrData => attrData.AttributeType == pluginAttributeType)
                     where info != null
                     let description = info.NamedArguments
                                           .SingleOrDefault(a => a.MemberName == "Description")
                     select new
                     {
                         type,
                         Name = (string) info.ConstructorArguments[0].Value,
                         Author = (string) info.ConstructorArguments[1].Value,
                         Description =
                             description == null ? null : description.TypedValue.Value
                     };

                foreach (var plugin in plugins)
                {
                    Console.WriteLine("Typ wtyczki: {0}", plugin.type.Name);
                    Console.WriteLine("Nazwa: {0}, autor {1}", plugin.Name, plugin.Author);
                    Console.WriteLine("Opis: {0}", plugin.Description);
                }
            }
        }

        public static void FindAttributes()
        {
            ShowPluginInformation(Path.GetDirectoryName(typeof(Example19).Assembly.Location));
        }
    }
}
