using Autofac;
using GreenTree.Nachtragsmanagement.Core;
using GreenTree.Nachtragsmanagement.Core.Plugins;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace GreenTree.Nachtragsmanagement.Services.Misc
{
    public class NotificationService : INotificationService
    {
        /// <summary>
        /// Loads all implementations of the INotificationPlugin
        /// </summary>
        public IEnumerable<INotificationPlugin> LoadNotificationPlugins()
        {
            var type = typeof(INotificationPlugin);
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            var types = assemblies
                .SelectMany(p => p.GetTypes())
                .Where(p => type.IsAssignableFrom(p) && !p.IsInterface)
                .Select(p => Activator.CreateInstance(p))
                .OfType<INotificationPlugin>()
                .ToList();

            return types;
        }

        /// <summary>
        /// Searches for all implementations of the INotificationPlugin
        /// </summary>
        public IEnumerable<INotificationPlugin> GetNotificationPlugins()
        {
            var notificationPlugins = Singleton<IContainer>.Instance.Resolve<IEnumerable<INotificationPlugin>>();

            if (notificationPlugins != null)
                return notificationPlugins;

            return LoadNotificationPlugins();
        }

        /// <summary>
        /// Gets a notification plugin by a specific name
        /// </summary>
        /// <param name="pluginSystemName">SystemName of notification plugin.</param>
        public INotificationPlugin GetNotificationPlugin(string pluginSystemName)
        {
            if (String.IsNullOrEmpty(pluginSystemName))
                return null;

            var notificationPlugin = Singleton<IContainer>.Instance.ResolveNamed<INotificationPlugin>(pluginSystemName);

            if (notificationPlugin != null)
                return notificationPlugin;

            var notificationPlugins = GetNotificationPlugins();

            if (notificationPlugins == null)
                return null;

            return notificationPlugins
                .FirstOrDefault(p => p.SystemName == pluginSystemName);
        }
    }
}