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

/*
 * Created on 15 juin 2005
 *
 */
package org.eclipse.mddi.modelbus.adapter.test.sample;

import java.util.Collection;

import org.apache.log4j.Logger;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.EcoreFactory;
import org.eclipse.emf.ecore.impl.EcorePackageImpl;
import org.eclipse.mddi.modelbus.adapter.infrastructure.LoggerConfigurator;
import org.eclipse.mddi.modelbus.adapter.infrastructure.model_manipulation.ModelUtil;
import org.eclipse.mddi.modelbus.adapter.user.ModelingServiceError;
import org.eclipse.mddi.modelbus.adapter.user.SessionNeeded;
import org.eclipse.mddi.modelbus.adapter.user.provider.GenericProvider;

/**
 * @author Prawee Sriplakich, Andrey Sadovykh (LIP6)
 *
 *
 */
public class SampleModelingServiceImpl implements GenericProvider {
    
    EcoreFactory fac = EcorePackageImpl.init().getEcoreFactory(); 
    private static Logger logger=Logger.getLogger(SampleModelingServiceImpl.class);

    /* (non-Javadoc)
     * @see org.eclipse.mddi.modelbus.adapter.tool.ServiceInvocation#execute(java.lang.String, java.lang.Object[])
     */
    public Object[] execute(String serviceName, Object[] parameterValues)
            throws SessionNeeded, ModelingServiceError {
        LoggerConfigurator.configure();
        if(serviceName.equalsIgnoreCase("createNewClass")) {
          return createNewClass(parameterValues);
        } 
        throw new ModelingServiceError("NoImplementation", null);
    }
    
    
    Object[] createNewClass(Object[] parameterValues) throws ModelingServiceError {
        LoggerConfigurator.configure();
        String newClassName = (String) parameterValues[0];
        Collection model = (Collection) parameterValues[1];
        logger.info("createNewClass input model = " + model );
        
        Collection classes = ModelUtil.findElementByType(model, "EClass");
        if(classes.size()>5) {          
            //test the mechanism for sending ModelingServiceError
            throw new ModelingServiceError("TooManyClasses", null);
        }
        
        EClass c = fac.createEClass();
        c.setName(newClassName);
        model.add(c);
        
        Object[] outputs = new Object[1];
        outputs[0] = model;
        
        logger.info("createNewClass output model= " + model );
        
        return outputs;        
    }
    

}
