/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 Bull S.A.
 * Contact: jonas-team@objectweb.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
 *
 * Initial developer(s):Helene Joanin, Christophe Ney
 * Contributor(s): Jeff Mesnil (security)
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */


package org.objectweb.jonas_ejb.deployment.api;

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

import org.objectweb.jonas_ejb.deployment.xml.MethodParams;
import org.objectweb.jonas_ejb.deployment.xml.MethodParam;

 /**
  * Class for deployment descriptors of methods.
  * Holds description of transaction attributes
 */
public class MethodDesc {

    /**
     * Set of constants for method transaction attribute
     */
    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"
    };

    /**
     * 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();
    private int securityStatus = APPLY_TO_BEAN;

    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"
    };
        
    /**
     * package protected default constructor
     */
    MethodDesc() {
    }

    /**
     * Protected copy constructor used by API
     */
    protected MethodDesc(MethodDesc object) {
        txAttribute = object.txAttribute;
        txAttributeStatus = object.txAttributeStatus;
        roleName = object.roleName;
        securityStatus = object.securityStatus;
    }
    
    /**
     * 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
     */
    void addRoleName (String rn, int securityStatus) 
        throws DeploymentDescException {
        // overwrite only if numerical value greater than existing one
        if (securityStatus < this.securityStatus)
            return;
        this.securityStatus = securityStatus;
        roleName.add(rn);
    }
    
    /**
     * 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 pclass, 
				   String mName, 
				   MethodParams patternMethodParams) {

        // If pclass don't match -> APPLY_TO_NOTHING
        if (pclass != null && !pclass.isAssignableFrom(meth.getDeclaringClass())) {
	    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 = ((MethodParam)i.next()).getValue();
            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
     */
    protected 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 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()]);
        if (!roleName.isEmpty()) {
            ret.append("\ngetSecurityStatus()="+APPLY_TO[securityStatus]);
            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();
    }

    /**
     * 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.objectweb.jonas_ejb.deployment.xml.Method m) {
        String s = new String();
        if (m.getMethodIntf() != null) {
            s = s.concat(m.getMethodIntf()+".");
        }
        s = s.concat(m.getMethodName().getValue());
        if (m.getMethodParams() != null) {
            s = s.concat("(");
            for (Iterator i = m.getMethodParams().getMethodParamList().iterator(); i.hasNext(); ) {
                s = s.concat(((MethodParam)i.next()).getValue());
                if (i.hasNext()) {
                    s = s.concat(",");
                }
            }
            s = s.concat(")");
        }
        return(s);
    }
}






