﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Practices.Unity;
using WishStore.Application;
using WishStore.Application.Impl;
using Radial;
using Radial.Boot;
using Radial.Persist;
using Radial.Persist.Nhs;
using Radial.Extensions;
using WishStore.Infras;
using Radial.Param;
using WishStore.Infras.Persist.Initializer;
using Radial.Persist.Nhs.Param;

namespace WishStore.Infras
{
    /// <summary>
    /// GeneralBootTask
    /// </summary>
    public class GeneralBootTask : IBootTask
    {
        /// <summary>
        /// System initialize process.
        /// </summary>
        public virtual void Initialize()
        {
            Components.Container.RegisterType<IParam, KvParam>();

            Components.Container.RegisterType<IUnitOfWork, ContextualUnitOfWork>();

#if SqlClient
            Components.Container.RegisterType<IFactoryPoolInitializer, SqlClientFactoryPoolInitializer>(new ContainerControlledLifetimeManager());
#elif MySql
           Components.Container.RegisterType<IFactoryPoolInitializer, MySqlFactoryPoolInitializer>(new ContainerControlledLifetimeManager());
#endif

            foreach (var type in typeof(GeneralBootTask).Assembly.GetTypes()
                .Where(o => o.CustomAttributes.Contains(x => x.AttributeType == typeof(RegisterInterfaceAttribute))))
            {
                var attr = type.GetCustomAttributes(typeof(RegisterInterfaceAttribute), false)[0] as RegisterInterfaceAttribute;

                if (!string.IsNullOrWhiteSpace(attr.Symbol))
                {
#if SqlClient
                    if (attr.Symbol == "SqlClient")
                        Components.Container.RegisterType(attr.InterfaceType, type);
#elif MySql
                     if (attr.Symbol == "MySql")
                        Components.Container.RegisterType(attr.InterfaceType, type);
#endif
                }
                else
                    Components.Container.RegisterType(attr.InterfaceType, type);
            }
        }

        /// <summary>
        /// Start system.
        /// </summary>
        public virtual void Start()
        {
            HibernateEngine.OpenAndBindSession();
        }

        /// <summary>
        /// Stop system.
        /// </summary>
        public virtual void Stop()
        {
            HibernateEngine.CloseAndUnbindSession();
        }
    }
}
