package minhhai2209.jirapluginconverter.plugin.condition;

import com.atlassian.plugin.PluginParseException;
import com.atlassian.plugin.web.Condition;
import com.fasterxml.jackson.databind.ObjectMapper;
import minhhai2209.jirapluginconverter.plugin.utils.HttpClientFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;

import java.util.Map;

public class RemoteCondition implements Condition {
  
  private Map<String, String> params;
  private String conditionUrl;
  private ObjectMapper om = new ObjectMapper();

  @Override
  public void init(Map<String, String> params) throws PluginParseException {
    this.params = params;
    this.conditionUrl = params.get("condition");
    
  }

  @Override
  public boolean shouldDisplay(Map<String, Object> context) {
    return conditionUrl == null || getRemoteCondition();
  }
  
  private boolean getRemoteCondition() {
    try {
      HttpClient client = HttpClientFactory.build();
      URIBuilder builder = new URIBuilder(conditionUrl);
      if (params != null) {
        for (String key : params.keySet()) {
          builder.addParameter(key, params.get(key));
        }
      }
      HttpGet httpGet = new HttpGet(builder.build());
      HttpResponse response = client.execute(httpGet);
      DisplayDto displayDto = om.readValue(response.getEntity().getContent(), DisplayDto.class);
      return displayDto.isShouldDisplay();
    } catch (Exception e) {
      //any exception will return false
    }
    
    return false;
  }

}

@@ -197,16 +197,94 @@
 Mapper;%0A
+import minhhai2209.jirapluginconverter.plugin.render.ParameterContextBuilder;%0A
 import m
@@ -1019,16 +1019,23 @@
 ndition(
+context
 );%0A  %7D%0A 
@@ -1077,21 +1077,236 @@
 ion(
-) %7B%0A    try %7B
+Map%3CString, Object%3E context) %7B%0A    try %7B%0A      Map%3CString, String%3E productContext = ParameterContextBuilder.buildContext(null, context, null);%0A      conditionUrl = ParameterContextBuilder.buildUrl(conditionUrl, productContext);%0A
 %0A   

support context params in condition