/**
 * Distributable under LGPL license.
 * See terms of license at gnu.org.
 *
 * Copyright (C)
 * <a href="http://www.inab.org">Spanish National Institute of Bioinformatics (INB)</a>
 * <a href="http://www.bsc.es">Barcelona Supercomputing Center (BSC)</a>
 * <a href="http://inb.bsc.es">Computational Node 6</a>
 */

package org.inb.biomoby.generator;

import org.inb.util.TemplateInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.TreeMap;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.xml.bind.JAXBException;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import org.inb.biomoby.shared.registry.Service;

/**
 * @author Dmitry Repchevsky
 */

public class ServiceGenerator
{
    private final static String DEFAULT_PACKAGE = "org.biomoby.service.ejb";
    private final static String DEFAULT_PATH = DEFAULT_PACKAGE.replace('.', '/') + '/';

    private final static String WSDL_TEMPLATE = "resources/template.wsdl";
    
    public ServiceGenerator() {}

    public void generateService(Service service, ZipOutputStream zip) throws TransformerConfigurationException, TransformerException, JAXBException, IOException
    {
        String serviceName = GeneratorUtil.getJavaClassName(service.getName());
        
        String ejb = GeneratorUtil.transform("resources/ejb3.xsl", service);
        
        ZipEntry ejbEntry = new ZipEntry(DEFAULT_PATH + serviceName + "Bean.java");
        zip.putNextEntry(ejbEntry);
        zip.write(ejb.getBytes());
        
        String ejbLocal = GeneratorUtil.transform("resources/ejb3local.xsl", service);

        ZipEntry ejbLocalEntry = new ZipEntry(DEFAULT_PATH + serviceName + "Local.java");
        zip.putNextEntry(ejbLocalEntry);
        zip.write(ejbLocal.getBytes());
                
        InputStream in = this.getClass().getClassLoader().getResourceAsStream(WSDL_TEMPLATE);
        
        Map paramz = new TreeMap();
        paramz.put("serviceName", serviceName);
        paramz.put("portName", serviceName + "Port");

        TemplateInputStream tmpl = new TemplateInputStream(in, paramz);
        
        ZipEntry wsdlEntry = new ZipEntry("META-INF/wsdl/" + serviceName + ".wsdl");
        zip.putNextEntry(wsdlEntry);

        int ch;
        while((ch = tmpl.read()) >= 0)
        {
            zip.write(ch);
        }
    }
}
