using System;
using System.Collections.Generic;
using System.Linq;
using log4net;
using Quadarax.Foundation.Common.Object.Bee.Core.Pattern;
using Quadarax.Foundation.Infrastructure.Layers;

namespace Quadarax.Foundation.Infrastructure
{
    internal class GlobalContainer : Singleton<GlobalContainer>
    {

        private GlobalLayer _global;
        private ILog _logger;

        public GlobalLayer RootLayer => _global;

        public GlobalContainer()
        {
            _logger = LogManager.GetLogger(GetType());
        }

        public void CreateGlobal<TGlobalLayer>(string globalLayerName,params object[] initialArgs) where TGlobalLayer : GlobalLayer
        {
            var ctorArgs = new List<object>();
            ctorArgs.Add(globalLayerName);
            ctorArgs.AddRange(initialArgs);

            _global = (GlobalLayer) Activator.CreateInstance(typeof(TGlobalLayer), ctorArgs.ToArray());
        }

        public string[] GetLayerNames()
        {
            var names = new List<string>(_global.GetChildLayerNames());
            names.Insert(0,_global.Name);
            return names.ToArray();
        }

        public Layer GetLayerByName(string layerName)
        {
            return _global.Name == layerName ? 
                _global :
                _global.FindChildLayer(layerName).FirstOrDefault();
        }


        public IEnumerable<TLayer> GetLayer<TLayer>() where TLayer : Layer
        {
            var layers = new List<TLayer>();
            if (_global.GetType() == typeof(TLayer))
                layers.Add(_global as TLayer);
            layers.AddRange(_global.FindChildLayer<TLayer>());
            return layers.ToArray();
        }  

        public string Dump()
        {
            return _global.Dump();
        }

        public string DumpContainer()
        {
            return _global.DumpContainer(true);
        }
    }
}
