/*
 * Copyright (c) 2018, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * WSO2 Inc. licenses this file to you 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.wso2.carbon.micro.integrator.management.apis;

import org.apache.axiom.om.OMElement;
import org.apache.axiom.om.util.AXIOMUtil;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.NameValuePair;
import org.apache.synapse.MessageContext;
import org.apache.synapse.config.SynapseConfiguration;
import org.apache.synapse.core.axis2.Axis2MessageContext;
import org.apache.synapse.inbound.InboundEndpoint;
import org.wso2.carbon.inbound.endpoint.internal.http.api.APIResource;

import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.stream.XMLStreamException;

import static org.wso2.carbon.micro.integrator.management.apis.Utils.getQueryParameters;

public class InboundEndpointResource extends APIResource {

    private static Log log = LogFactory.getLog(InboundEndpointResource.class);

    private static final String ROOT_ELEMENT_INBOUND_ENDPOINTS = "<InboundEndpoints></InboundEndpoints>";
    private static final String COUNT_ELEMENT = "<Count></Count>";
    private static final String LIST_ELEMENT = "<List></List>";

    private static final String ROOT_ELEMENT_INBOUND_ENDPOINT = "<InboundEndpoint></InboundEndpoint>";
    private static final String NAME_ELEMENT = "<Name></Name>";
    private static final String PROTOCOL_ELEMENT = "<Protocol></Protocol>";
    private static final String STAT_ELEMENT = "<Stats></Stats>";
    private static final String TRACING_ELEMENT = "<Tracing></Tracing>";

    private static final String PARAMETERS_ELEMENT = "<Parameters></Parameters>";
    private static final String PARAMETER_ELEMENT = "<Parameter></Parameter>";
    private static final String KEY_ELEMENT = "<Name></Name>";
    private static final String VALUE_ELEMENT = "<Value></Value>";

    public InboundEndpointResource(String urlTemplate){
        super(urlTemplate);
    }

    @Override
    public Set<String> getMethods() {
        Set<String> methods = new HashSet<String>();
        methods.add("GET");
        methods.add("POST");
        return methods;
    }

    @Override
    public boolean invoke(MessageContext messageContext) {

        buildMessage(messageContext);
//        log.info("Message : " + messageContext.getEnvelope());

        org.apache.axis2.context.MessageContext axis2MessageContext =
                ((Axis2MessageContext) messageContext).getAxis2MessageContext();

        List<NameValuePair> queryParameter = getQueryParameters(axis2MessageContext);

        try {
            // if query params exists retrieve data about specific inbound endpoint
            if (null != queryParameter) {
                for (NameValuePair nvPair : queryParameter) {
                    if (nvPair.getName().equals("inboundEndpointName")) {
                        populateInboundEndpointData(messageContext, nvPair.getValue());
                    }
                }
            } else {
                populateInboundEndpointList(messageContext);
            }

            axis2MessageContext.removeProperty("NO_ENTITY_BODY");
        } catch (XMLStreamException e) {
            log.error("Error occurred while processing response", e);
        }
        return true;
    }

    private void populateInboundEndpointList(MessageContext messageContext) throws XMLStreamException {

        org.apache.axis2.context.MessageContext axis2MessageContext =
                ((Axis2MessageContext) messageContext).getAxis2MessageContext();

        SynapseConfiguration configuration = messageContext.getConfiguration();

        Collection<InboundEndpoint> inboundEndpoints = configuration.getInboundEndpoints();

        OMElement rootElement = AXIOMUtil.stringToOM(ROOT_ELEMENT_INBOUND_ENDPOINTS);
        OMElement countElement = AXIOMUtil.stringToOM(COUNT_ELEMENT);
        OMElement listElement = AXIOMUtil.stringToOM(LIST_ELEMENT);

        countElement.setText(String.valueOf(inboundEndpoints.size()));
        rootElement.addChild(countElement);

        rootElement.addChild(listElement);

        for (InboundEndpoint inboundEndpoint : inboundEndpoints) {

            OMElement inboundElement = AXIOMUtil.stringToOM(ROOT_ELEMENT_INBOUND_ENDPOINT);
            OMElement nameElement = AXIOMUtil.stringToOM(NAME_ELEMENT);
            OMElement protocolElement = AXIOMUtil.stringToOM(PROTOCOL_ELEMENT);

            nameElement.setText(inboundEndpoint.getName());
            inboundElement.addChild(nameElement);

            protocolElement.setText(inboundEndpoint.getProtocol());
            inboundElement.addChild(protocolElement);

            listElement.addChild(inboundElement);
        }
        axis2MessageContext.getEnvelope().getBody().addChild(rootElement);
    }

    private void populateInboundEndpointData(MessageContext messageContext, String inboundEndpointName) throws XMLStreamException {

        org.apache.axis2.context.MessageContext axis2MessageContext =
                ((Axis2MessageContext) messageContext).getAxis2MessageContext();

        OMElement rootElement = getInboundEndpointByName(messageContext, inboundEndpointName);

        if (null != rootElement) {
            axis2MessageContext.getEnvelope().getBody().addChild(rootElement);
        } else {
            axis2MessageContext.setProperty("HTTP_SC", "404");
        }
    }

    private OMElement getInboundEndpointByName(MessageContext messageContext, String inboundEndpointName) throws XMLStreamException {

        SynapseConfiguration configuration = messageContext.getConfiguration();
        InboundEndpoint ep = configuration.getInboundEndpoint(inboundEndpointName);
        return convertInboundEndpointToOMElement(ep);
    }

    private OMElement convertInboundEndpointToOMElement(InboundEndpoint inboundEndpoint) throws XMLStreamException{

        if (null == inboundEndpoint) {
            return null;
        }

        OMElement rootElement = AXIOMUtil.stringToOM(ROOT_ELEMENT_INBOUND_ENDPOINT);
        OMElement nameElement = AXIOMUtil.stringToOM(NAME_ELEMENT);
        OMElement protocolElement = AXIOMUtil.stringToOM(PROTOCOL_ELEMENT);
        OMElement statElement = AXIOMUtil.stringToOM(STAT_ELEMENT);
        OMElement tracingElement = AXIOMUtil.stringToOM(TRACING_ELEMENT);
        OMElement parametersElement = AXIOMUtil.stringToOM(PARAMETERS_ELEMENT);

        nameElement.setText(inboundEndpoint.getName());
        rootElement.addChild(nameElement);

        protocolElement.setText(inboundEndpoint.getProtocol());
        rootElement.addChild(protocolElement);

        String statisticState = inboundEndpoint.getAspectConfiguration().isStatisticsEnable() ? "enabled" : "disabled";
        statElement.setText(statisticState);
        rootElement.addChild(statElement);

        String tracingState = inboundEndpoint.getAspectConfiguration().isTracingEnabled() ? "enabled" : "disabled";
        tracingElement.setText(tracingState);
        rootElement.addChild(tracingElement);

        rootElement.addChild(parametersElement);

        Map<String, String> params = inboundEndpoint.getParametersMap();

        for (Map.Entry<String,String> param : params.entrySet()) {

            OMElement parameterElement = AXIOMUtil.stringToOM(PARAMETER_ELEMENT);

            OMElement keyElement = AXIOMUtil.stringToOM(KEY_ELEMENT);
            OMElement valueElement = AXIOMUtil.stringToOM(VALUE_ELEMENT);

            keyElement.setText(param.getKey());
            valueElement.setText(param.getValue());

            parameterElement.addChild(keyElement);
            parameterElement.addChild(valueElement);
            parametersElement.addChild(parameterElement);
        }
        return rootElement;
    }
}
