[assembly: WebActivator.PreApplicationStartMethod(typeof(Gazallion.MigraineManager.Web.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(Gazallion.MigraineManager.Web.App_Start.NinjectWebCommon), "Stop")]

namespace Gazallion.MigraineManager.Web.App_Start
{
    using System;
    using System.Web;

    using Microsoft.Web.Infrastructure.DynamicModuleHelper;

    using Ninject;
    using Ninject.Web.Common;
    using Gazallion.MigraineManager.Service.I;
    using Gazallion.MigraineManager.Service;
    using Gazallion.MigraineManager.Data.I;
    using Gazallion.MigraineManager.Data.SqlServer;
    using Gazallion.MigraineManager.Data.SqlServer.Models;
    
    using System.Web.Http;
    using Gazallion.MigraineManager.IOC;

    public static class NinjectWebCommon 
    {
        private static readonly Bootstrapper bootstrapper = new Bootstrapper();

        /// <summary>
        /// Starts the application
        /// </summary>
        public static void Start() 
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
            bootstrapper.Initialize(CreateKernel);
        }
        
        /// <summary>
        /// Stops the application.
        /// </summary>
        public static void Stop()
        {
            bootstrapper.ShutDown();
        }
        
        /// <summary>
        /// Creates the kernel that will manage your application.
        /// </summary>
        /// <returns>The created kernel.</returns>
        private static IKernel CreateKernel()
        {
            var kernel = new StandardKernel();
            kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

            NinjectDependencyResolver dependencyResolver = new NinjectDependencyResolver(kernel);

            // Install our Ninject-based IDependencyResolver into the Web API config
            GlobalConfiguration.Configuration.DependencyResolver = dependencyResolver;

            RegisterServices(kernel);
            return kernel;
        }

        /// <summary>
        /// Load your modules or register your services here!
        /// </summary>
        /// <param name="kernel">The kernel.</param>
        private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<IRepository>().To<EFRepository<GazallionMigraineDataDbContext>>();
            kernel.Bind<IUserService>().To<UserService>();
        }        
    }
}
