using Edge.Core.Processor.Dispatcher;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;

namespace Edge.Core.UniversalApi
{
    public static class UniversalApiHubFactory
    {
        public static UniversalApiHub Create(IServiceProvider services)
        {
            var communicationProviderTypes = new List<Type>();
            foreach (var ass in ObjectInstanceCreator.CurrentDomainAssemblies)
            {
                try
                {
                    //var ass = Assembly.LoadFrom(ai.FullName);
                    var t = ass.GetTypes().Where(t => typeof(ICommunicationProvider).IsAssignableFrom(t)
                        && !t.IsInterface);
                    if (t != null && t.Any()) communicationProviderTypes.AddRange(t);
                }
                catch
                { }
            }

            var communicationProviders = new List<ICommunicationProvider>();
            foreach (var pType in communicationProviderTypes)
            {
                //here assume ICommunicationProvider must have 1 parameter constructor of IServiceProvider, need refine.
                //var providerInstance =
                //    Activator.CreateInstance(pType, new[] { services.BuildServiceProvider() }) as ICommunicationProvider;
                var providerInstance = ObjectInstanceCreator.Create(pType.FullName, "", new Type[] { }, new object[] { services });
                //Activator.CreateInstance(pType, null) as ICommunicationProvider;
                communicationProviders.Add((ICommunicationProvider)providerInstance);
            }

            return new Edge.Core.UniversalApi.UniversalApiHub(communicationProviders, services);
        }
    }
}