package com.hubspot.dropwizard.guice;

import com.google.common.base.Optional;
import com.google.inject.AbstractModule;
import com.google.inject.Provider;
import com.google.inject.Provides;
import com.yammer.dropwizard.config.Configuration;
import com.yammer.dropwizard.config.Environment;

public class DropwizardEnvironmentModule<T extends Configuration> extends AbstractModule {
	private T configuration;
	private Environment environment;
	private Class<? super T> configurationClass;

	public DropwizardEnvironmentModule(Class<T> configurationClass) {
		this.configurationClass = configurationClass;
	}

	@Override
	protected void configure() {
		Provider<T> provider = new CustomConfigurationProvider();
		bind(configurationClass).toProvider(provider);
		if (configurationClass != Configuration.class) {
			bind(Configuration.class).toProvider(provider);
		}
	}

	public void setEnvironmentData(T configuration, Environment environment) {
		this.configuration = configuration;
		this.environment = environment;
	}

	@Provides
	public Environment providesEnvironment() {
		return environment;
	}

	private class CustomConfigurationProvider implements Provider<T> {
		@Override
		public T get() {
			return configuration;
		}
	}
}

@@ -113,16 +113,60 @@
 Module;%0A
+import com.google.inject.CreationException;%0A
 import c
@@ -227,16 +227,54 @@
 ovides;%0A
+import com.google.inject.spi.Message;%0A
 import c
@@ -366,16 +366,42 @@
 nment;%0A%0A
+import java.util.Arrays;%0A%0A
 public c
@@ -1182,130 +1182,621 @@
 %7B%0A%09%09
-return environment;%0A%09%7D%0A%0A%09private class CustomConfigurationProvider implements Provider%3CT%3E %7B%0A%09%09@Override%0A%09%09public T get() %7B
+if (environment == null) %7B%0A%09%09%09throw new CreationException(Arrays.asList(new Message(%22The dropwizard environment has not yet been set. This is likely caused by trying to access the dropwizard environment during the bootstrap phase.%22)));%0A%09%09%7D%0A%09%09return environment;%0A%09%7D%0A%0A%09private class CustomConfigurationProvider implements Provider%3CT%3E %7B%0A%09%09@Override%0A%09%09public T get() %7B%0A%09%09%09if (configuration == null) %7B%0A%09%09%09%09throw new CreationException(Arrays.asList(new Message(%22The dropwizard configuration has not yet been set. This is likely caused by trying to access the dropwizard environment during the bootstrap phase.%22)));%0A%09%09%09%7D
 %0A%09%09%09

Throw exceptions if accessing configuration/environment during bootstrap phase.