/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2006 Bull S.A.S.
 * Contact: jonas-team@ow2.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed 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.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.ow2.jonas.generators.genic;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import org.ow2.jonas.deployment.ejb.BeanDesc;
import org.ow2.jonas.deployment.ejb.EntityDesc;
import org.ow2.jonas.deployment.ejb.EntityJdbcCmp1Desc;
import org.ow2.jonas.deployment.ejb.EntityJdbcCmp2Desc;
import org.ow2.jonas.deployment.ejb.SessionStatefulDesc;
import org.ow2.jonas.deployment.ejb.SessionStatelessDesc;
import org.ow2.jonas.lib.util.Log;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import org.objectweb.jorm.metainfo.api.Manager;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

/**
 * This class allows to generate the source of : the class that implements the
 * Enterprise bean's remote interface, the class that implements the Enterprise
 * bean's home interface, the class that implements the Enterprise bean's local
 * interface, the class that implements the Enterprise bean's localhome
 * interface, the class of the Entity Handle in case of entity, or the extended
 * class of the Bean for persistence in case of entity with CMP, via a Velocity
 * template of the given Enterprise Java Bean.
 * @author Helene Joanin : Initial developer
 */
class Source {

    /**
     * home source
     */
    static final int HOME = 0;
    /**
     * local home source
     */
    static final int LOCAL_HOME = 1;
    /**
     * remote source
     */
    static final int REMOTE = 2;
    /**
     * local source
     */
    static final int LOCAL = 3;
    /**
     * entity handle source
     */
    static final int ENTITY_HANDLE = 4;
    /**
     * CMP1 or CMP2 entity bean source
     */
    static final int ENTITY_CMP_JDBC = 5;
    /**
     * interface coherence source for CMP2 entity
     */
    static final int ITF_COH_CMP2_ENTITY = 7;

    /**
     * service endpoint source
     */
    static final int SERVICE_ENDPOINT = 9;

    /**
     * service endpoint home source
     */
    static final int SERVICE_ENDPOINT_HOME = 10;

    /**
     * Bean Deployment Description
     */
    private BeanDesc dd = null;

    /**
     * Name of the generated source file
     */
    private String srcFileName = null;

    /**
     * Generated source file type
     */
    private int srcType;

    /**
     * Velocity engine
     */
    private VelocityEngine vEngine = null;

    /**
     * Velocity context
     */
    private VelocityContext vctx = null;

    /**
     * logger
     */
    private Logger logger = null;

    /**
     * Source Constructor
     * @param beanDesc deployment descriptor of the bean
     * @param fileName name of the source file to generate
     * @param type source's type (HOME, LOCAL_HOME, REMOTE, ...)
     * @param ve Velocity engine to use
     * @exception GenICException In error case
     */
    Source(BeanDesc beanDesc, String fileName, int type, VelocityEngine ve, Manager mgr) throws GenICException {
        dd = beanDesc;
        srcFileName = fileName;
        srcType = type;
        vctx = VContextFactory.create(dd, srcType, mgr);
        vEngine = ve;
        logger = Log.getLogger(Log.JONAS_GENIC_PREFIX);
        // Trace of the Velocity Context
        Logger vLogger = Log.getLogger(Log.JONAS_GENIC_VELOCITY_PREFIX);
        if (vLogger.getCurrentIntLevel() == BasicLevel.DEBUG) {
            vLogger.log(BasicLevel.DEBUG, "Source(..,fileName=" + fileName + ", type = " + type + ", ..)");
            vLogger.log(BasicLevel.DEBUG, "VELOCITY CONTEXT = \n(" + VContextFactory.toString(vctx) + "\n)");
        }
    }

    /**
     * Generates the java source
     * @throws GenICException in error case
     */
    void generate() throws GenICException {

        String tmplName = null;
        Template tmpl = null;
        FileWriter fwriter = null;

        switch (srcType) {
            case HOME:
                if (dd instanceof EntityDesc) {
                    tmplName = "JEntityHome.vm";
                } else if (dd instanceof SessionStatefulDesc) {
                    tmplName = "JStatefulHome.vm";
                } else if (dd instanceof SessionStatelessDesc) {
                    tmplName = "JStatelessHome.vm";
                }
                break;
            case LOCAL_HOME:
                if (dd instanceof EntityDesc) {
                    tmplName = "JEntityLocalHome.vm";
                } else if (dd instanceof SessionStatefulDesc) {
                    tmplName = "JStatefulLocalHome.vm";
                } else if (dd instanceof SessionStatelessDesc) {
                    tmplName = "JStatelessLocalHome.vm";
                }
                break;
            case REMOTE:
                if (dd instanceof EntityDesc) {
                    tmplName = "JEntityRemote.vm";
                } else if (dd instanceof SessionStatefulDesc) {
                    tmplName = "JStatefulRemote.vm";
                } else if (dd instanceof SessionStatelessDesc) {
                    tmplName = "JStatelessRemote.vm";
                }
                break;
            case LOCAL:
                if (dd instanceof EntityDesc) {
                    tmplName = "JEntityLocal.vm";
                } else if (dd instanceof SessionStatefulDesc) {
                    tmplName = "JStatefulLocal.vm";
                } else if (dd instanceof SessionStatelessDesc) {
                    tmplName = "JStatelessLocal.vm";
                }
                break;
            case SERVICE_ENDPOINT:
                if (dd instanceof SessionStatelessDesc) {
                    tmplName = "JServiceEndpoint.vm";
                }
                break;
            case SERVICE_ENDPOINT_HOME:
                if (dd instanceof SessionStatelessDesc) {
                    tmplName = "JServiceEndpointHome.vm";
                }
                break;
            case ENTITY_HANDLE:
                if (dd instanceof EntityDesc) {
                    tmplName = "JEntityHandle.vm";
                }
                break;
            case ENTITY_CMP_JDBC:
                if (dd instanceof EntityJdbcCmp1Desc) {
                    tmplName = "JEntityCmpJdbc.vm";
                }
                if (dd instanceof EntityJdbcCmp2Desc) {
                    tmplName = "JEntityCmp2.vm";
                }
                break;
            case ITF_COH_CMP2_ENTITY:
                if (dd instanceof EntityJdbcCmp2Desc) {
                    tmplName = "JEntityCmp2CoherenceItf.vm";
                }
                break;
            default:
                break;
        }
        if (tmplName == null) {
            throw new GenICException("No template for  '" + srcFileName + " !!!'");
        }

        String name = null;
        try {
            // must add the package name
            name = this.getClass().getPackage().getName().replace('.', '/') + "/" + tmplName;
            tmpl = vEngine.getTemplate(name);
        } catch (Exception e) {
            throw new GenICException("Cannot get " + name, e);
        }

        try {
            // Create before the parent directory
            File fs = new File(srcFileName);
            File fdir = fs.getParentFile();
            if (fdir != null) {
                if (!fdir.exists()) {
                    if (!fdir.mkdirs()) {
                        throw new IOException("Cannot create the directory '" + fdir.getPath() + "'");
                    }
                }
            }
            fwriter = new FileWriter(srcFileName);
        } catch (IOException e) {
            e.printStackTrace();
            throw new GenICException("Cannot create the '" + srcFileName + "' source file", e);
        }
        logger.log(BasicLevel.DEBUG, "Generate the file " + srcFileName);
        try {
            tmpl.merge(vctx, fwriter);
        } catch (Exception e) {
            throw new GenICException("Cannot generate the '" + srcFileName + "' source from the '" + tmplName
                    + "' template", e);
        }

        try {
            fwriter.flush();
            fwriter.close();
        } catch (IOException e) {
            throw new GenICException("Cannot close the '" + srcFileName + "' source file", e);
        }
    }

}