/*
 * Copyright 2015 Norbert Potocki (norbert.potocki@nort.pl)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.cfg4j.provider;

import static java.util.Objects.requireNonNull;

import com.github.drapostolos.typeparser.NoSuchRegisteredParserException;
import com.github.drapostolos.typeparser.TypeParser;
import com.github.drapostolos.typeparser.TypeParserException;
import org.cfg4j.source.ConfigurationSource;
import org.cfg4j.source.context.environment.Environment;
import org.cfg4j.source.context.environment.MissingEnvironmentException;
import org.cfg4j.validator.BindingValidator;

import java.lang.reflect.Proxy;
import java.util.NoSuchElementException;
import java.util.Properties;

/**
 * Basic implementation of {@link ConfigurationProvider}. To construct this provider use {@link ConfigurationProviderBuilder}.
 */
class SimpleConfigurationProvider implements ConfigurationProvider {

  private final ConfigurationSource configurationSource;
  private final Environment environment;

  /**
   * {@link ConfigurationProvider} backed by provided {@link ConfigurationSource} and using {@code environment}
   * to select environment. To construct this provider use {@link ConfigurationProviderBuilder}.
   *
   * @param configurationSource source for configuration
   * @param environment         {@link Environment} to use
   */
  SimpleConfigurationProvider(ConfigurationSource configurationSource, Environment environment) {
    this.configurationSource = requireNonNull(configurationSource);
    this.environment = requireNonNull(environment);
  }

  @Override
  public Properties allConfigurationAsProperties() {
    try {
      return configurationSource.getConfiguration(environment);
    } catch (IllegalStateException | MissingEnvironmentException e) {
      throw new IllegalStateException("Couldn't fetch configuration from configuration source", e);
    }
  }

  @Override
  public <T> T getProperty(String key, Class<T> type) {
    String propertyStr = getProperty(key);

    try {
      TypeParser parser = TypeParser.newBuilder().build();
      return parser.parse(propertyStr, type);
    } catch (TypeParserException | NoSuchRegisteredParserException e) {
      throw new IllegalArgumentException("Unable to cast value \'" + propertyStr + "\' to " + type, e);
    }
  }

  @Override
  public <T> T getProperty(String key, GenericTypeInterface genericType) {
    String propertyStr = getProperty(key);

    try {
      TypeParser parser = TypeParser.newBuilder().build();
      @SuppressWarnings("unchecked")
      T property = (T) parser.parseType(propertyStr, genericType.getType());
      return property;
    } catch (TypeParserException | NoSuchRegisteredParserException e) {
      throw new IllegalArgumentException("Unable to cast value \'" + propertyStr + "\' to " + genericType, e);
    }
  }

  private String getProperty(String key) {
    try {

      Object property = configurationSource.getConfiguration(environment).get(key);

      if (property == null) {
        throw new NoSuchElementException("No configuration with key: " + key);
      }

      return property.toString();

    } catch (IllegalStateException e) {
      throw new IllegalStateException("Couldn't fetch configuration from configuration source for key: " + key, e);
    }
  }

  @Override
  public <T> T bind(String prefix, Class<T> type) {
    @SuppressWarnings("unchecked")
    T proxy = (T) Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[]{type}, new BindInvocationHandler(this, prefix));

    new BindingValidator().validate(proxy, type);

    return proxy;
  }

  @Override
  public String toString() {
    return "SimpleConfigurationProvider{" +
        "configurationSource=" + configurationSource +
        ", environment=" + environment +
        '}';
  }
}

@@ -1098,24 +1098,57 @@
 Validator;%0A%0A
+import java.lang.reflect.Method;%0A
 import java.
@@ -3891,24 +3891,1298 @@
 %3CT%3E type) %7B%0A
+    return bind(this, prefix, type);%0A  %7D%0A%0A  /**%0A   * Create an instance of a given %7B@code type%7D that will be bound to the %7B@code configurationProvider%7D. Each time configuration changes the%0A   * bound object will be updated with the new values. Use %7B@code prefix%7D to specify the relative path to configuration%0A   * values. Please note that each method of returned object can throw runtime exceptions. For details see javadoc for%0A   * %7B@link BindInvocationHandler#invoke(Object, Method, Object%5B%5D)%7D.%0A   *%0A   * @param %3CT%3E    interface describing configuration object to bind%0A   * @param prefix relative path to configuration values (e.g. %22myContext%22 will map settings %22myContext.someSetting%22,%0A   *               %22myContext.someOtherSetting%22)%0A   * @param type   %7B@link Class%7D for %7B@code %3CT%3E%7D%0A   * @return configuration object bound to this %7B@link ConfigurationProvider%7D%0A   * @throws NoSuchElementException   when the provided %7B@code key%7D doesn't have a corresponding config value%0A   * @throws IllegalArgumentException when property can't be coverted to %7B@code type%7D%0A   * @throws IllegalStateException    when provider is unable to fetch configuration value for the given %7B@code key%7D%0A   */%0A  %3CT%3E T bind(ConfigurationProvider configurationProvider, String prefix, Class%3CT%3E type) %7B%0A
     @Suppres
@@ -5316,20 +5316,37 @@
 Handler(
-this
+configurationProvider
 , prefix

allow to use non-this configuration provider when binding in SimpleConfigurationProvider