// Copyright (c) 1996-2002 Brian D. Carlstrom

package bdc.scheme.procedure;

import bdc.scheme.Scheme;
import bdc.scheme.SchemeException;
import bdc.scheme.Stack;
import bdc.scheme.exception.ArgumentCountException;
import bdc.scheme.exception.ArgumentTypeException;
import bdc.scheme.expression.ProcedureN;

/**
    Primitive for Class.getDeclaredMethod
*/
public class ClassGetMethod extends ProcedureN
{
    public Object applyN (int n, Stack stack) throws SchemeException
    {
        if (n < 2) {
            throw new ArgumentCountException(this, 2, n);
        }

        Object o1 = stack.array[stack.inUse-1];
        Object o2 = stack.array[stack.inUse-2];

        Class  clazz = Scheme.clazz(o1, this);
        String name  = Scheme.string(o2, this);

        Class[] parameters = new Class[n-2];
        for (int i = 3; i <= n ; i++) {
            parameters[i-3] = Scheme.clazz(stack.array[stack.inUse-i], this);
        }

        try {
            try {
                return clazz.getMethod(name, parameters);
            }
            catch (SecurityException e) {
                return null;
            }
        }
        catch (NoSuchMethodException e) {
            throw new ArgumentTypeException(this,
                                            "method that exists",
                                            name);
        }
    }
}
