package org.wso2.carbon.apimgt.rest.api.publisher.v1.common.template;

import org.apache.axis2.Constants;
import org.apache.velocity.VelocityContext;
import org.wso2.carbon.apimgt.api.APIManagementException;
import org.wso2.carbon.apimgt.api.model.API;
import org.wso2.carbon.apimgt.api.model.APIProduct;
import org.wso2.carbon.apimgt.impl.template.APITemplateException;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Set the transport config context
 */
public class TransportConfigContext extends ConfigContextDecorator {

    private API api;
    private APIProduct apiProduct;

    public TransportConfigContext(ConfigContext context, API api) {
        super(context);
        this.api = api;
    }

    public TransportConfigContext(ConfigContext context, APIProduct apiProduct) {
        super(context);
        this.apiProduct = apiProduct;
    }

    @Override
    public void validate() throws APITemplateException, APIManagementException {
        super.validate();
    }

    @Override
    public VelocityContext getContext() {
        VelocityContext context = super.getContext();

        String transportsString = "";

        if (api != null) {
            transportsString = api.getTransports();
        } else if (apiProduct != null) {
            transportsString = apiProduct.getTransports();
        }

        setTransportInVelocityContext(context, transportsString);

        return context;
    }

    private void setTransportInVelocityContext(VelocityContext context, String transportsString) {
        if (transportsString.contains(",")) {
            List<String> transports = new ArrayList<String>(Arrays.asList(transportsString.split(",")));
            if(transports.contains(Constants.TRANSPORT_HTTP) && transports.contains(Constants.TRANSPORT_HTTPS)){
                context.put("transport","");
            }
        }else{
            context.put("transport", transportsString);
        }
    }
}

@@ -99,16 +99,60 @@
 stants;%0A
+import org.apache.commons.lang.StringUtils;%0A
 import o
@@ -342,16 +342,65 @@
 roduct;%0A
+import org.wso2.carbon.apimgt.impl.APIConstants;%0A
 import o
@@ -1644,16 +1644,348 @@
 tring) %7B
+%0A%0A        if (StringUtils.isNotEmpty(api.getApiSecurity()) &&%0A                (api.getApiSecurity().contains(APIConstants.API_SECURITY_MUTUAL_SSL) %7C%7C%0A                        api.getApiSecurity().contains(APIConstants.API_SECURITY_MUTUAL_SSL_MANDATORY))) %7B%0A            context.put(%22transport%22, %22https%22);%0A            return;%0A        %7D
 %0A       
@@ -2142,16 +2142,17 @@
       if
+ 
 (transpo
@@ -2240,16 +2240,17 @@
 _HTTPS))
+ 
 %7B%0A      
@@ -2283,16 +2283,17 @@
 nsport%22,
+ 
 %22%22);%0A   
@@ -2312,20 +2312,22 @@
        %7D
+ 
 else
+ 
 %7B%0A      

add mutualSSL not support in default api