package com.wikia.gradle;

import com.orbitz.consul.Consul;
import com.orbitz.consul.util.ClientUtil;

import java.net.URI;
import java.util.HashMap;

public class ConsulKeyValueConfig {
  public static final String ENV_KEY = "CONSUL_KEY_VALUE_CONFIG_SOURCE";

  protected Consul consul;
  protected HashMap<String, String> config;
  protected String configFolder;

  public ConsulKeyValueConfig(String host, int port, String app, String env) {
    this(Consul.newClient(host, port), getConfigFolder(app, env));
  }

  public ConsulKeyValueConfig(String host, int port, String configFolder) {
    this(Consul.newClient(host, port), configFolder);
  }

  public ConsulKeyValueConfig(Consul consul, String app, String env) {
    this(consul, getConfigFolder(app, env));
  }

  public ConsulKeyValueConfig(Consul consul, String configFolder) {
    this.consul = consul;
    this.configFolder = configFolder;
  }

  public HashMap<String, String> getConfig() {
    if (config != null) {
      return config;
    }

    config = new HashMap<>();

    try {
      consul.keyValueClient().getValues(configFolder).stream()
          .filter(v -> getConfigKey(v.getKey()) != null)
          .forEach(v -> {
            String key = getConfigKey(v.getKey());
            String value = ClientUtil.decodeBase64(v.getValue());
            config.put(key, value);
          });
    } catch (Exception e) {
      return null;
    }

    return config;
  }

  public String get(String key) {
    return getConfig().get(key);
  }

  protected String getConfigKey(String key) {
    String remove = configFolder + "/";

    if (key.length() <= remove.length()) {
      return null;
    }

    return key.substring(remove.length());
  }

  public static ConsulKeyValueConfig fromEnv() {
    try {
      URI uri = new URI(System.getenv(ENV_KEY));
      return new ConsulKeyValueConfig(uri.getHost(),
                                      uri.getPort(),
                                      uri.getPath().substring(1));
    } catch (Exception e) {
      return null;
    }
  }

  protected static String getConfigFolder(String app, String env) {
    return "config/"+app+"/"+env;
  }
}

@@ -96,16 +96,74 @@
 tUtil;%0A%0A
+import org.slf4j.Logger;%0Aimport org.slf4j.LoggerFactory;%0A%0A
 import j
@@ -1446,35 +1446,157 @@
  e) %7B%0A      
-return null
+Logger logger = LoggerFactory.getLogger(ConsulKeyValueConfig.class);%0A      logger.warn(%22Count not fetch consul key/value configs%22, e)
 ;%0A    %7D%0A%0A   
@@ -2314,29 +2314,47 @@
 urn 
-%22config/%22+app+%22/%22+
+String.format(%22config/%25s/%25s%22, app, 
 env
+)
 ;%0A  

use string.format and return empty config hash when an error occurs in fetching configs /cc @sqreek