/*
   Copyright 2007 Attila Szegedi

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/
package org.dynalang.mop.beans;

import java.lang.reflect.Member;

import org.dynalang.mop.CallProtocol;
import org.dynalang.mop.BaseMetaobjectProtocol.Result;

/**
 * @author Attila Szegedi
 * @version $Id: $
 */
class OverloadedFixArgMethod<T extends Member> extends OverloadedMethod<T>
{

    void onAddSignature(T member, Class<?>[] argTypes) {
    };
    
    void updateSignature(int l) {
    };
    
    void afterSignatureAdded(int l) {
    };

    Object createInvocation(Object target, Object[] args, CallProtocol callProtocol) {
        if(args == null) {
            // null is treated as empty args
            args = DynamicMethod.NULL_ARGS;
        }
        int l = args.length;
        boolean argsCloned = false;
	Class<?>[][] marshalTypes = getMarshalTypes();
        if(marshalTypes.length <= l) {
            return OverloadedDynamicMethod.NO_SUCH_METHOD;
        }
        Class<?>[] types = marshalTypes[l];
        if(types == null) {
            return OverloadedDynamicMethod.NO_SUCH_METHOD;
        }
        assert types.length == l;
        // Marshal the arguments
        for(int i = 0; i < l; ++i) {
            Object src = args[i];
            Object dst = callProtocol.representAs(src, types[i]);
            if(dst == Result.noAuthority || dst == Result.noRepresentation) {
                return OverloadedDynamicMethod.NO_SUCH_METHOD;
            }
            if(dst != src) {
                if(!argsCloned) {
                    args = args.clone();
                }
                args[i] = dst;
            }
        }
        
        Object objMember = getMemberForArgs(args, false);
        if(objMember instanceof Member) {
            return new Invocation<T>(target, (T)objMember, args);
        }
        return objMember; // either NOT_FOUND or AMBIGUOUS
    }
}
