/*
 * $RCSfile: SampleSessionTool.java,v $
 * $Date: 2006/01/26 14:52:19 $
 * $Revision: 1.4 $
 * $Author: andreys $
 */

/*
 * 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.
 */

/*
 * SampleSessionTool.java Add description 
 * 
 * @author Andrey Sadovykh (LIP6)
 * @version $Revision: 1.4 $ $Date: 2006/01/26 14:52:19 $
 */
package org.eclipse.mddi.modelbus.adapter.test.session;

import java.util.Collection;
import java.util.Hashtable;
import java.util.Map;
import java.util.Properties;
import java.util.Vector;

import org.apache.log4j.Logger;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EcoreFactory;
import org.eclipse.emf.ecore.impl.EcorePackageImpl;
import org.eclipse.mddi.modelbus.adapter.infrastructure.model_manipulation.ModelUtil;
import org.eclipse.mddi.modelbus.adapter.user.AdapterStub;
import org.eclipse.mddi.modelbus.adapter.user.InvalidSession;
import org.eclipse.mddi.modelbus.adapter.user.ModelingServiceError;
import org.eclipse.mddi.modelbus.adapter.user.impl.AdapterStubImpl;
import org.eclipse.mddi.modelbus.adapter.user.provider.GenericSessionProvider;

/*
 * SampleSessionTool
 * 
 */

public class SampleSessionTool implements GenericSessionProvider {

    Collection model;

    EcoreFactory fac = EcorePackageImpl.init().getEcoreFactory();

    private static Logger logger = Logger.getLogger(SampleSessionTool.class);

    private static int sessionCounter = 0;
    
    private static Vector sessions = new Vector();

    private static Map session2packageName = new Hashtable();

    /**
     * 
     */
    public SampleSessionTool() {
        super();
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.mddi.modelbus.adapter.user.provider.GenericSessionProvider#executeSession(java.lang.String,
     *      java.lang.Object[], java.lang.String)
     */
public Object[] executeSession(String serviceName,
            Object[] parameterValues, String sessionID) throws InvalidSession,
            ModelingServiceError {
        logger.info("Execute in session(" + sessionID + ")");
        logger.info("Service name is [" + serviceName + "]");
        logger.info("value [0] is " + parameterValues[0]);

        if (!sessions.contains(sessionID)){
            throw new InvalidSession();
        } else if (serviceName.equals("openPackage")) {
            String packageName = (String) parameterValues[0];
            session2packageName.put(sessionID, packageName);
            return new Object[0];
        } else if (serviceName.equals("addNewClass")) {
            String newClassName = (String) parameterValues[0];
            model = (Collection) parameterValues[1];
            EClass c = fac.createEClass();
            c.setName(newClassName);

            
            
            
            EPackage pack = getPackage((String) session2packageName
                    .get(sessionID));
            EList list = pack.getEClassifiers();
            list.add(c);
            

            Object[] outputs = new Object[1];
            outputs[0] = model;

            return outputs;

        }

        return null;
    }
    public EPackage getPackage(String packageName) throws ModelingServiceError{
        
        if (packageName ==null) {
            throw new ModelingServiceError("Package is not yet open", this);
        }
        
        logger.debug("Package Name:"+packageName);

        // check model, whether the package is already inside
        EPackage p = (EPackage) ModelUtil.findElementByName(model, packageName);

        // if not exist, create
        if (p == null) {
            p = fac.createEPackage();
            p.setName(packageName);
            model.add(p);
        }

        return p;

    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.mddi.modelbus.adapter.user.provider.GenericSessionProvider#newSession()
     */
    public String newSession() {
        sessionCounter++;
        String sessionId = (new Integer(sessionCounter)).toString();
        sessions.add(sessionId);
        logger.info("New session is started ID=" + sessionId);
        return sessionId;
    }

    /*
     * (non-Javadoc)
     * 
     * @see org.eclipse.mddi.modelbus.adapter.user.provider.GenericSessionProvider#endSession(java.lang.String)
     */
    public void endSession(String sessionID) throws InvalidSession {
        if (!sessions.contains(sessionID))
            throw new InvalidSession();
        logger.info("End for session with ID=" + sessionID);

    }

    public static boolean isStarted = false;

    public static void main(String args[]) {

        if (isStarted)
            return;

        String registry_loc;
        if (args.length > 0) {
            registry_loc = args[0];
        } else {
            registry_loc = "http://localhost:8082/modelbus/modelwareRegistry";
        }

        String desc_file;
        if (args.length > 1) {
            desc_file = args[1];
        } else {
            desc_file = "./src/org/eclipse/mddi/modelbus/adapter/test/session/session_tool.description";
        }

        try {

            Properties p = new Properties();
            p.put(AdapterStub.PROP_REGISTRY_LOCATION, registry_loc);
            p.put(AdapterStub.PROP_TOOL_DESC_FILE, desc_file);

            AdapterStub adapter = new AdapterStubImpl(p);

            GenericSessionProvider provider = new SampleSessionTool();

            adapter.getToolStub().setSessionProvider(provider);

            adapter.deploy();
            logger.info("Session tool is available");
        } catch (Exception e) {
            e.printStackTrace();
            System.exit(0);
        }

    }
}
