/*
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you 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.codehaus.groovy.reflection;

import groovy.lang.GroovyRuntimeException;
import groovy.lang.MetaMember;
import org.codehaus.groovy.runtime.FormatHelper;
import org.codehaus.groovy.runtime.InvokerInvocationException;

import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Modifier;

/**
 * Caches reflection information about a single constructor for fast lookup and invocation.
 * <p>
 * Extends {@link ParameterTypes} to manage parameter type information and implements
 * {@link groovy.lang.MetaMember} for meta-programming support. Provides methods to invoke
 * constructors with argument coercion and error handling.
 */
public class CachedConstructor extends ParameterTypes implements MetaMember {

    private final CachedClass clazz;
    private final Constructor cachedConstructor;

    /**
     * Constructs a {@code CachedConstructor} for the given constructor within a cached class.
     *
     * @param clazz the cached class that declares this constructor
     * @param c the Java constructor to cache
     */
    public CachedConstructor(final CachedClass clazz, final Constructor c) {
        this.clazz = clazz;
        this.cachedConstructor = c;
    }

    /**
     * Constructs a {@code CachedConstructor} for the given Java constructor.
     * Automatically resolves the cached class from the constructor's declaring class.
     *
     * @param c the Java constructor to cache
     */
    public CachedConstructor(final Constructor c) {
        this(ReflectionCache.getCachedClass(c.getDeclaringClass()), c);
    }

    @Override
    protected Class[] getPT() {
        return cachedConstructor.getParameterTypes();
    }

    /**
     * Returns the name of the constructor (same as the declaring class name).
     *
     * @return the constructor name
     */
    @Override
    public String getName() {
        return cachedConstructor.getName();
    }

    /**
     * Returns the modifiers of this constructor (e.g., public, private, protected).
     * See {@link java.lang.reflect.Modifier} for modifier constants.
     *
     * @return the constructor modifiers
     */
    @Override
    public int getModifiers() {
        return cachedConstructor.getModifiers();
    }

    /**
     * Returns whether this constructor is synthetic (generated by the compiler).
     *
     * @return {@code true} if this constructor is synthetic; {@code false} otherwise
     */
    @Override
    public boolean isSynthetic() {
        return cachedConstructor.isSynthetic();
    }

    /**
     * Returns the string representation of this cached constructor.
     *
     * @return a string representation of the underlying constructor
     */
    @Override
    public String toString() {
        return cachedConstructor.toString();
    }

    //--------------------------------------------------------------------------

    /**
     * Finds a {@code CachedConstructor} corresponding to the specified Java constructor
     * by searching the cached constructors of its declaring class.
     *
     * @param constructor the constructor to find
     * @return the cached constructor
     * @throws RuntimeException if the constructor is not found in the cache
     */
    public static CachedConstructor find(Constructor constructor) {
        CachedConstructor[] constructors = ReflectionCache.getCachedClass(constructor.getDeclaringClass()).getConstructors();
        for (CachedConstructor cachedConstructor : constructors) {
            if (cachedConstructor.cachedConstructor.equals(constructor))
                return cachedConstructor;
        }
        throw new RuntimeException("Couldn't find method: " + constructor);
    }

    /**
     * Invokes this constructor with the specified arguments after coercing them to the parameter types.
     *
     * @param argumentArray the arguments to pass to the constructor
     * @return a new instance of the class
     * @throws GroovyRuntimeException if the invocation fails
     */
    public Object doConstructorInvoke(Object[] argumentArray) {
        argumentArray = coerceArgumentsToClasses(argumentArray);
        return invoke(argumentArray);
    }

    /**
     * Invokes this constructor with the specified arguments.
     * Handles access control, abstract class checks, and exception wrapping.
     *
     * @param argumentArray the arguments to pass to the constructor
     * @return a new instance of the class
     * @throws GroovyRuntimeException if invocation fails, access is denied, or the class is abstract
     */
    public Object invoke(Object[] argumentArray) {
        Constructor constr = cachedConstructor;

        if (isConstructorOfAbstractClass()) {
            throw createException("failed to invoke constructor: ", constr, argumentArray, new InstantiationException(), true);
        }

        makeAccessibleIfNecessary();

        try {
            return constr.newInstance(argumentArray);
        } catch (InvocationTargetException e) {
            throw e.getCause() instanceof RuntimeException ? (RuntimeException)e.getCause() : new InvokerInvocationException(e);
        } catch (IllegalArgumentException e) {
            throw createException("failed to invoke constructor: ", constr, argumentArray, e, false);
        } catch (IllegalAccessException e) {
            throw createException("could not access constructor: ", constr, argumentArray, e, false);
        } catch (Exception e) {
            if (e instanceof RuntimeException)
                throw (RuntimeException)e;
            else
                throw createException("failed to invoke constructor: ", constr, argumentArray, e, true);
        }
    }

    private static GroovyRuntimeException createException(String init, Constructor constructor, Object[] argumentArray, Throwable e, boolean setReason) {
        return new GroovyRuntimeException(
                init
                        + constructor
                        + " with arguments: "
                        + FormatHelper.toArrayString(argumentArray)
                        + " reason: "
                        + e,
                setReason ? e : null);
    }

    /**
     * Returns the cached class that declares this constructor.
     *
     * @return the cached class
     */
    public CachedClass getCachedClass() {
        return clazz;
    }

    /**
     * Returns the class that declares this constructor.
     *
     * @return the declaring class
     */
    public Class getDeclaringClass() {
        return cachedConstructor.getDeclaringClass();
    }

    /**
     * Returns the underlying Java constructor object, making it accessible if necessary.
     *
     * @return the cached constructor
     */
    public Constructor getCachedConstructor() {
        makeAccessibleIfNecessary();
        return cachedConstructor;
    }

    private boolean makeAccessibleDone = false;
    private void makeAccessibleIfNecessary() {
        if (!makeAccessibleDone) {
            ReflectionUtils.makeAccessibleInPrivilegedAction(cachedConstructor);
            makeAccessibleDone = true;
        }
    }

    private boolean isConstructorOfAbstractClass() {
        return Modifier.isAbstract(cachedConstructor.getDeclaringClass().getModifiers());
    }


}
