using Microsoft.Practices.Unity.Configuration;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;

namespace UnityConfigurationTree
{
    public static class UnityConfExt
    {
        const string basePath = @"unity";
        public static void Load(IUnityContainer container)
        {
            var rsRoot = RelationShip.Load($@"{basePath}\relationship.json");
            Configure(rsRoot, container);
        }
        public static IUnityContainer Load()
        {
            IUnityContainer container = new UnityContainer();
            Load(container);
            return container;
        }
        static void Configure(RelationShip rs, IUnityContainer container)
        {
            foreach (var path in rs.Path)
            {
                var confSection = GetSection($@"{basePath}\{path}");
                confSection.Configure(container);
            }
            if (rs.Children != null)
            {
                foreach (var rsChildren in rs.Children)
                {
                    var subContainer = container.CreateChildContainer();
                    container.RegisterInstance(rsChildren.Name, subContainer);
                    Configure(rsChildren, subContainer);
                }
            }
        }
        static UnityConfigurationSection GetSection(string path)
        {
            var exeConfigurationFileMap = new ExeConfigurationFileMap { ExeConfigFilename = path };
            System.Configuration.Configuration configuration =
                ConfigurationManager.OpenMappedExeConfiguration(exeConfigurationFileMap, ConfigurationUserLevel.None);
            var unityConfigurationSection = configuration.GetSection("unity") as UnityConfigurationSection;
            return unityConfigurationSection;
        }
   
    }
    
}
