/**
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999-2004 Bull S.A.
 * 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: MethodDesc.java 15428 2008-10-07 11:20:29Z sauthieg $
 * --------------------------------------------------------------------------
 */



package org.ow2.jonas.deployment.ejb;

import java.lang.reflect.Method;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;

import org.ow2.jonas.deployment.common.DeploymentDescException;
import org.ow2.jonas.deployment.ejb.xml.MethodParams;


/**
 * Class to hold meta-information related to bean and home methods.
 * @author Christophe Ney [cney@batisseurs.com] : Initial developer
 * @author Helene Joanin: fix a bug about select method select method is a bean's method which name begins with ejbSelect,
 *                        (and not home interface method as finder method).
 */
public class MethodDesc {

    /**
     * Set of constants for method transaction attribute
     */
    public static final int TX_NULL          = -1;
    public static final int TX_NOT_SET       = 0;
    public static final int TX_NOT_SUPPORTED = 1;
    public static final int TX_REQUIRED      = 2;
    public static final int TX_SUPPORTS      = 3;
    public static final int TX_REQUIRES_NEW  = 4;
    public static final int TX_MANDATORY     = 5;
    public static final int TX_NEVER         = 6;


    private static final String[] ATTR = {
        "TX_NOT_SET",
        "TX_NOT_SUPPORTED",
        "TX_REQUIRED",
        "TX_SUPPORTS",
        "TX_REQUIRES_NEW",
        "TX_MANDATORY",
        "TX_NEVER"
    };

    /**
     * default value for undefined transaction attribute for sessions and entities
     */
    protected static final String TX_STR_DEFAULT_VALUE = "Supports";

    /**
     * default value for undefined transaction attribute for message driven beans
     */
    protected static final String TX_STR_DEFAULT_VALUE_4_MDB = "NotSupported";

    /**
     * value for undefined transaction attribute
     */
    private int txAttribute = TX_NOT_SET;
    private int txAttributeStatus = APPLY_TO_BEAN;

    // Array of String representing the roles which can execute the method of this MethodDesc
    private HashSet roleName = new HashSet();

    public static final int APPLY_TO_NOTHING = 0;
    public static final int APPLY_TO_BEAN = 1;
    public static final int APPLY_TO_CLASS = 2;
    public static final int APPLY_TO_BEAN_METHOD_NAME = 3;
    public static final int APPLY_TO_CLASS_METHOD_NAME = 4;
    public static final int APPLY_TO_BEAN_METHOD = 5;
    public static final int APPLY_TO_CLASS_METHOD = 6;

    protected static final String[] APPLY_TO = {
        "APPLY_TO_NOTHING",
        "APPLY_TO_BEAN",
        "APPLY_TO_CLASS",
        "APPLY_TO_BEAN_METHOD_NAME",
        "APPLY_TO_CLASS_METHOD_NAME",
        "APPLY_TO_BEAN_METHOD",
        "APPLY_TO_CLASS_METHOD"
    };

    private Method meth;
    private Class classDef;
    private int index;

    protected BeanDesc beanDesc;

    private boolean isFinder = false;
    private boolean isEjbSelect = false;
    private boolean isFindByPrimaryKey = false;

    /**
     * This method was marked as excluded in ejb-jar.xml ?
     */
    private boolean excluded = false;

    /**
     * constructor to be used by parent node
     */
    public MethodDesc(BeanDesc beanDesc, Method meth, Class clDef, int index) {
        this.meth = meth;
        this.classDef = clDef;
        this.index = index;
        this.beanDesc = beanDesc;
        isFindByPrimaryKey = MethodDesc.isFindByPrimaryKey(meth);
        isFinder = isFinder(meth);
        isEjbSelect = isEjbSelect(meth);
    }

    /**
     * get a unique index of the method for the bean
     */
    public int getIndex() {
        return index;
    }

    public void setIndex(int idx) {
        index = idx;
    }

    /**
     * access if the method is a finder
     * @return true for finder methods
     */
    public boolean isFinder() {
        return isFinder;
    }

    /**
     * access if the method is <code>findByPrimaryKey</code>
     * @return true for the <code>findByPrimaryKey</code> method
     */
    public boolean isFindByPrimaryKey() {
        return isFindByPrimaryKey;
    }


    /**
     * access if the method is a select
     * @return true for select methods
     */
    public boolean isEjbSelect() {
        return isEjbSelect;
    }


    /**
     * Overwrite TxAttribute
     * @param transAttribute new value for txAttribute
     * @param status applicability of given transAttribute parameter
     */
    void overwriteTxAttribute(String transAttribute, int status) throws DeploymentDescException {
        // overwrite only if numerical value greater than existing one
        if (status < this.txAttributeStatus) {
            return;
        }
        setTxAttribute(transAttribute);
        txAttributeStatus = status;
    }

    /**
     * Set TxAttribute with given value
     */
    void setTxAttribute(String transAttribute) throws DeploymentDescException {
        if (transAttribute.equals("NotSupported")) {
            txAttribute = TX_NOT_SUPPORTED;
        } else if (transAttribute.equals("Required")) {
            txAttribute = TX_REQUIRED;
        } else if (transAttribute.equals("Supports")) {
            txAttribute = TX_SUPPORTS;
        } else if (transAttribute.equals("RequiresNew")) {
            txAttribute = TX_REQUIRES_NEW;
        } else if (transAttribute.equals("Mandatory")) {
            txAttribute = TX_MANDATORY;
        } else if (transAttribute.equals("Never")) {
            txAttribute = TX_NEVER;
        } else {
            throw new DeploymentDescException(transAttribute
                                              + " is not a valid trans-attribute value");
        }
    }

    /**
     * Add a role name to the role names which can execute the method
     * @param rn role name to add
     */
    void addRoleName (String rn) {
        roleName.add(rn);
    }

    /**
     * Evaluate method pattern maching as defined in the EJB specifications
     * @return one of the <code>APPLY_TO_*</code> values.
     */
    public int matchPattern(Class pclass, String mName, MethodParams patternMethodParams) {
        return matchPattern(getMethod(), classDef, pclass, mName, patternMethodParams);
    }

    /**
     * Get the status of applicability for a given pattern to a method
     * @return status of applicability APPLY_TO_NOTHING,APPLY_TO_BEAN,APPLY_TO_CLASS,APPLY_TO_METHOD_NAME,APPLY_TO_METHOD
     */
    public static int matchPattern(java.lang.reflect.Method meth,
                                   Class classMeth,
                                   Class pclass,
                                   String mName,
                                   MethodParams patternMethodParams) {

        // If pclass don't match -> APPLY_TO_NOTHING
        if (pclass != null && !pclass.isAssignableFrom(classMeth)) {
            return APPLY_TO_NOTHING;
        }

        // class is enough
        if (mName.equals("*")) {
            return (pclass == null) ? APPLY_TO_BEAN : APPLY_TO_CLASS;
        }

        // method name does not match
        if (!mName.equals(meth.getName())) {
            return APPLY_TO_NOTHING;
        }

        // no params specified (name test is enough)
        if (patternMethodParams == null) {
            return (pclass == null) ? APPLY_TO_BEAN_METHOD_NAME : APPLY_TO_CLASS_METHOD_NAME;
        }

        Class pars[] = meth.getParameterTypes();
        List pattPars = patternMethodParams.getMethodParamList();
        // number of parameters does not match
        if (pars.length != pattPars.size()) {
            return APPLY_TO_NOTHING;
        }
        Iterator i = pattPars.iterator();
        for (int ii = 0; ii < pars.length; ii++) {
            String cName = (String) i.next();
            if (!getClassName(pars[ii]).equals(cName)) {
                return APPLY_TO_NOTHING;
            }
        }
        return (pclass == null) ? APPLY_TO_BEAN_METHOD : APPLY_TO_CLASS_METHOD;
    }

    /**
     * Returns common name of a given type <BR>
     * For example it returns int[] for an array of int
     * @return String with the name of the given type
     */
    private static String getClassName(Class c) {
        String name;
        if (c.isArray()) {
            name = getClassName(c.getComponentType()) + "[]";
        } else {
            name = c.getName();
        }
        return (name);
    }



    /**
     * Get the container transaction attribute that match the method
     * @return Constant value within list :
     * TX_NOT_SUPPORTED,TX_REQUIRED,TX_SUPPORTS,TX_REQUIRES_NEW,TX_MANDATORY,TX_NEVER,TX_NOT_SET
     */
    public int getTxAttribute() {
        return txAttribute;
    }

    /**
     * Get the container transaction attribute that match the method
     * @return Constant value within list :
     * APPLY_TO_NOTHING, APPLY_TO_BEAN, APPLY_TO_CLASS, APPLY_TO_BEAN_METHOD_NAME,
     * APPLY_TO_CLASS_METHOD_NAME, APPLY_TO_BEAN_METHOD, APPLY_TO_CLASS_METHOD
     */
    public int getTxAttributeStatus() {
        return txAttributeStatus;
    }

    /**
     * String representation of the transactionnal attribute
     * @return String representation of this transactionnal attribute
     */
    public static String getTxAttributeName(int value) {
        if ((value < 0) || (value > ATTR.length)) {
            throw new Error(value + " is not a valid TxAttribute");
        }
        return ATTR[value];
    }

    /**
     * String representation of the transactionnal attribute
     * @return String representation of this transactionnal attribute
     */
    public String getTxAttributeName() {
        return ATTR[txAttribute];
    }

    /**
     * String representation of the roles which can execute the method
     * @return Array of String representing the roles which can execute the method
     */
    public String[] getRoleName () {
        if (roleName.isEmpty()) {
            return new String[0];
        }
        Object[] o = roleName.toArray();
        String[] rn =  new String[o.length];
        for (int i = 0; i < rn.length; i++) {
            rn[i] = (String) o[i];
        }
        return rn;
    }

    /**
     * String representation of the given element <method>
     * @param  m an element <method>
     * @return String representation of the given element method
     */
    public static String methodElementToString(org.ow2.jonas.deployment.ejb.xml.Method m) {
        return methodElementToString(m.getMethodIntf(), m.getMethodName(), m.getMethodParams());
    }

    /**
     * get a String representation of a method from it's XML representation
     */
    protected static String methodElementToString(String intf, String name, MethodParams params) {
        String s = new String();
        if (intf != null) {
            s = s.concat(intf + ".");
        }
        s = s.concat(name);
        if (params != null) {
            s = s.concat("(");
            for (Iterator i = params.getMethodParamList().iterator(); i.hasNext();) {
                s = s.concat((String) i.next());
                if (i.hasNext()) {
                    s = s.concat(",");
                }
            }
            s = s.concat(")");
        }
        return (s);
    }

    /**
     * get a String representation of a method from the reflection object
     */
    public static String toString(Method m) {
        StringBuffer ret = new StringBuffer();
        ret.append(m.getDeclaringClass().getName());
        ret.append('.');
        ret.append(m.getName());
        ret.append('(');
        Class[] params = m.getParameterTypes();
        for (int i = 0; i < params.length; i++) {
            ret.append(getClassName(params[i]));
            if (i == params.length - 1) {
                break;
            }
            ret.append(',');
        }
        ret.append(')');
        return ret.toString();
    }

    /**
     * return the method to which the meta-information applies
     */
    public Method getMethod() {
        return meth;
    }

    /**
     * get the parent node
     */
    public BeanDesc getBeanDesc() {
        return beanDesc;
    }

    /**
     * access if a method is a finder
     */
    public static boolean isFinder(Method meth) {
        return (meth.getName().startsWith("find")
                && (javax.ejb.EJBHome.class.isAssignableFrom(meth.getDeclaringClass())
                    || javax.ejb.EJBLocalHome.class.isAssignableFrom(meth.getDeclaringClass())));
    }

    /**
     * access if a method is findByPrimaryKey
     */
    public static boolean isFindByPrimaryKey(Method meth) {
        return (meth.getName().equals("findByPrimaryKey")
                && (javax.ejb.EJBHome.class.isAssignableFrom(meth.getDeclaringClass())
                    || javax.ejb.EJBLocalHome.class.isAssignableFrom(meth.getDeclaringClass())));
    }

    /**
     * access if a method is a select
     */
    public static boolean isEjbSelect(Method meth) {
        return (meth.getName().startsWith("ejbSelect")
                && javax.ejb.EntityBean.class.isAssignableFrom(meth.getDeclaringClass()));
    }

    /**
     * String representation of the object for test purpose
     * @return String representation of this object
     */
    public String toString() {
        StringBuffer ret = new StringBuffer();
        ret.append("\ngetTxAttribute()       = " + ATTR[getTxAttribute()]);
        ret.append("\ngetTxAttributeStatus() = " + APPLY_TO[getTxAttributeStatus()]);
        ret.append("\nMethodIndex            = " + index);
        ret.append("\nmeth                   = " + toString(meth));
        ret.append("\nisFinder               = " + isFinder);
        ret.append("\nisEjbSelect            = " + isEjbSelect);
        ret.append("\nisFindByPrimaryKey     = " + isFindByPrimaryKey);
        if (!roleName.isEmpty()) {
            ret.append("\ngetRoleName()          = [");
            String [] rn = getRoleName();
            for (int i = 0; i < rn.length - 1; i++) {
                ret.append (rn[i] + ", ");
            }
            ret.append(rn[rn.length - 1] + "]");
            ret.append("\n");
        }
        return ret.toString();
    }

    /**
     * @return true if this method is excluded (in DD), else false
     */
    public boolean isExcluded() {
        return excluded;
    }
    /**
     * Sets the excluded attribute.
     * @param excluded true of false
     */
    public void setExcluded(boolean excluded) {
        this.excluded = excluded;
    }
}






