/*
 * Copyright (c) 2002-2003 IST-2004-2006-511731 ModelWare - ModelBus.
 * All rights reserved.
 *
 * This software is published under the terms of the ModelBus Software License
 * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
 * the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * A copy of ModelBus Software License is provided with this distribution in
 * doc/LICENSE.txt file.
 */

package org.eclipse.mddi.modelbus.adapter.test.registry;

import java.util.Vector;


import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPFault;

import org.apache.log4j.Logger;
import org.eclipse.mddi.modelbus.adapter.infrastructure.LoggerConfigurator;
import org.eclipse.mddi.modelbus.adapter.infrastructure.transport.marshal.ws.SoapUtil;
import org.eclipse.mddi.modelbus.adapter.infrastructure.transport.server.ws.EndPoint;
import org.eclipse.mddi.modelbus.adapter.infrastructure.transport.server.ws.EndPointManagerImpl;
import org.eclipse.mddi.modelbus.adapter.infrastructure.transport.server.ws.ServerManager;





/**
 * This is a temporary implementation of Registry component.
 * It purpose is for testing Adapter.
 * 
 * 
 * @author Prawee Sriplakich, Andrey Sadovykh (LIP6)
 *
 */
public class BasicRegistry implements EndPoint {
    
    /**
     * The relative part that belongs to this EndPoint begins with "modelwareRegistry"
     */
    public static final String REL_PATH = "modelwareRegistry";
    
    private static Logger logger = Logger.getLogger(BasicRegistry.class);
    
    private static int port = 8082;

    private static Vector data = new Vector();
    
    public static String getUrl() {
        return "http://localhost:" +port +"/"  +ServerManager.DEFAULT_CONTEXT + "/" +REL_PATH;        
    }
    
    public static void start(int _port)throws Exception {
        BasicRegistry.port = _port;
        start();
    }
    
    
    public static void start() throws Exception{
        LoggerConfigurator.configure();
        if(isStarted) return;
        isStarted = true;  
        BasicRegistry r = new BasicRegistry();
        
        ServerManager.getInstance().getServer(port);
        EndPointManagerImpl.getInstance().putEndPoint(REL_PATH, r);
        
        logger.info("Registry is running");
        
    }
    
    

    public static void stop() {
        //WsBindingManager.getInstance().stopAllServers();       
        
    }

    
    
    public void execute(String urlPath, SOAPEnvelope request, SOAPEnvelope response) throws javax.xml.soap.SOAPException {
        SOAPBody requestbody = request.getBody();
        
        logger.debug("Request: "+request);
        
        SOAPElement reqTopElem = SoapUtil.getFirstChild(requestbody);
      	String serviceName = reqTopElem.getLocalName();

 //       logger.debug("Service: "+serviceName);
        
        SOAPBody responsebody = response.getBody(); 
        responsebody.addNamespaceDeclaration("reg", "http://impl.registry.modelware");
        
        if(serviceName.equalsIgnoreCase("ToolInstance")) {
            //registerTool
            //parameter value is a string according to WSDL
            String value = reqTopElem.getValue();
            data.add(value);
            logger.debug(value);
            
            responsebody.addChildElement("registerToolReturn", "registerTool" + "Reponse"); 
            
        
        } else if(
                serviceName.equalsIgnoreCase("lookupAllModelingServices")
             || serviceName.equalsIgnoreCase("lookupModelingServicesByName")
             || serviceName.equalsIgnoreCase("lookupAllModelingServiceInterfaces")          
             || serviceName.equalsIgnoreCase("modelingServiceInterfaceName")
        ) {
            
            //SOAPElement resTopElem = responsebody.addChildElement("reg" , "lookupAllModelingServiceInterfaces" + "Response");            
            SOAPElement paramElem = responsebody.addChildElement("lookupAllModelingServiceInterfacesReturn");
            
                   
//            logger.debug("Get list size="+data.size());
            for(int i=0; i<data.size(); i++) {
                SOAPElement itemElem = paramElem.addChildElement("item");
                itemElem.addTextNode((String)data.get(i));
            }
            
            
        } else if( serviceName.equalsIgnoreCase("deregisterTool")) {
            
        } else {
           SOAPFault f = responsebody.addFault();  
           f.setFaultString("Registry: unsupported service " + serviceName);
           logger.error("Registry: unsupported service " + serviceName);
        }
        
//        logger.debug("Response: "+response);

    }   
    
    public static boolean isStarted = false;

    public static void main(String[] args) {
        LoggerConfigurator.configure();
        if (args==null && args.length>0) {
            port = Integer.parseInt(args[0]);            
        }             
        try {
            BasicRegistry.start();
        }catch(Exception e){
            logger.error("Registry was not started:",e);
            System.exit(1);
            
        }
        
        
    }
}
