/*
 * Copyright 2002-2008 the original author or authors.
 *
 * 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.springframework.config.java.internal.model;

import static java.lang.String.format;
import static org.springframework.config.java.internal.util.AnnotationExtractionUtils.extractMethodAnnotation;
import static org.springframework.config.java.util.DefaultScopes.PROTOTYPE;
import static org.springframework.config.java.util.DefaultScopes.SINGLETON;

import java.lang.annotation.Annotation;
import java.util.List;

import org.springframework.config.java.annotation.Bean;
import org.springframework.config.java.annotation.aop.ScopedProxy;
import org.springframework.config.java.internal.util.AnnotationExtractionUtils;
import org.springframework.config.java.internal.util.MethodAnnotationPrototype;


/** TODO: JAVADOC */
public class BeanMethod extends AbstractValidatableAnnotatedMethod<Bean> {

    private static final Bean DEFAULT_BEAN_ANNOTATION = extractMethodAnnotation(Bean.class, new MethodAnnotationPrototype() {
            @Bean
            public void targetMethod() { }
        }.getClass());

    public BeanMethod(String name, Annotation... annotations) { this(name, 0, annotations); }

    /**
     * Creates a new BeanMethod object.
     *
     * @param  name
     * @param  modifiers
     * @param  annotations  list of any JavaConfig-specific annotations (must be within
     *                      org.springframework.config.java)
     */
    public BeanMethod(String name, int modifiers, Annotation... annotations) {
        super(name, modifiers, annotations);
    }

    /**
     * for testing convenience.
     */
    BeanMethod(String name) { this(name, DEFAULT_BEAN_ANNOTATION); }

    /**
     * for testing convenience.
     */
    BeanMethod(String name, int modifiers) { this(name, modifiers, DEFAULT_BEAN_ANNOTATION); }

    /**
     * Determines whether this array of method <var>annotations</var> represents a Bean method.
     */
    public static boolean identifyAsBeanMethod(Annotation[] annotations) {
        return (AnnotationExtractionUtils.findAnnotation(Bean.class, annotations) != null);
    }

    public boolean isScopedProxy() { return getScopedProxyMetadata() != null; }

    public ScopedProxy getScopedProxyMetadata() {
        for(Annotation annotation : getAnnotations())
            if(annotation instanceof ScopedProxy)
                return (ScopedProxy) annotation;

        return null;
    }

    @Override
    public void detectUsageErrors(List<UsageError> errors) {
        super.detectUsageErrors(errors);

        Object[] compatibleAnnotationTypes = new Object[] { Bean.class, ScopedProxy.class };

        for (Annotation anno : getAnnotations())
            if (!arrayContains(compatibleAnnotationTypes, anno.annotationType()))
                errors.add(new IncompatibleAnnotationError(anno));

        if (this.isScopedProxy())
            if (getMetadata().scope().equals(SINGLETON) || getMetadata().scope().equals(PROTOTYPE))
                errors.add(new InvalidScopedProxyDeclarationError());

    }

    private boolean arrayContains(Object[] array, Object item) {
        for (Object candidate : array)
            if (candidate.equals(item))
                return true;

        return false;
    }


    // NOTE: may apply to other types of methods than just BeanMethod in the future
    // e.g.: AutoBean.  When this happens, move this error into a superclass test.common
    // to both bean method types.
    public class InvalidScopedProxyDeclarationError extends UsageError {
        public InvalidScopedProxyDeclarationError() {
            super(getDeclaringClass(), getLineNumber());
        }

        @Override
        public String getDescription() {
            return format("method %s contains an invalid annotation declaration: @%s "
                          + "cannot be used on a singleton/prototype bean",
                          getName(), ScopedProxy.class.getSimpleName());
        }
    }

}
