using Edge.Core.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Edge.Core.Processor.Dispatcher.ProcessorLoader
{
    public static class ProcessorLoaderFactory
    {
        public static IProcessorLoader Create(IServiceProvider services)
        {
            IProcessorLoader loader = null;
            //List<Type> processorLoaderTypes = new List<Type>();
            //foreach (var ass in ObjectInstanceCreator.CurrentDomainAssemblies)
            //{
            //    try
            //    {
            //        //var ass = Assembly.LoadFrom(ai.FullName);
            //        var t = ass.GetTypes().Where(t => typeof(IProcessorLoader).IsAssignableFrom(t)
            //            && !t.IsInterface);
            //        if (t != null && t.Any()) processorLoaderTypes.AddRange(t);
            //    }
            //    catch
            //    { }
            //}

            if ((Configurator.Default.DeviceProcessorConfiguration?.Processor?.Count ?? 0) == 0)
            {
                var loaderTypeStr = Configurator.Default.MetaConfiguration
                    ?.Parameter?.FirstOrDefault(p => p.Name.Equals("processorLoaderType", StringComparison.OrdinalIgnoreCase))?.Value;
                if (string.IsNullOrEmpty(loaderTypeStr))
                    loader = new DbJSonLoader(services);
                else
                    loader = ObjectInstanceCreator.Create(loaderTypeStr, null, new Type[] { }, new object[] { services }) as IProcessorLoader;
            }
            else
            {
                loader = new LegacySettingsXmlFileLoader(services);
            }

            return loader;
        }
    }

    public static class ProcessorMetaConfigAccessorFactory
    {
        public static IProcessorMetaConfigAccessor Create(IServiceProvider services)
        {
            var loader = services.GetService(typeof(IProcessorLoader));
            return loader as IProcessorMetaConfigAccessor;
        }
    }
}
