/*
 * 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 org.springframework.config.java.internal.util.AnnotationExtractionUtils.findAnnotation;

import org.springframework.util.Assert;

import java.lang.annotation.Annotation;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;


/** TODO: JAVADOC */
abstract class AbstractValidatableAnnotatedMethod<A extends Annotation> extends JavaConfigMethod
        implements ValidatableMethod, AnnotatedMethod<A> {

    private final A metadata;

    public AbstractValidatableAnnotatedMethod(String name, int modifiers, Annotation... annotations) {
        super(name, modifiers, annotations);
        Type superclass = getClass().getGenericSuperclass();
        if (!(superclass instanceof ParameterizedType))
            throw new IllegalStateException("must subclass parameterized type");

        ParameterizedType pSuper = (ParameterizedType) superclass;
        Type[] typeArgs = pSuper.getActualTypeArguments();

        Type arg = typeArgs[0];

        @SuppressWarnings("unchecked")
        Class<A> annoType = (Class<A>) arg;

        this.metadata = findAnnotation(annoType, annotations);
        Assert.notNull(metadata, "could not find target annotation @" + annoType.getName());
    }

    @Override
    public A getMetadata() { return metadata; }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = super.hashCode();
        result = (prime * result) + ((metadata == null) ? 0 : metadata.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;

        if (!super.equals(obj))
            return false;

        if (getClass() != obj.getClass())
            return false;

        AbstractValidatableAnnotatedMethod<?> other = (AbstractValidatableAnnotatedMethod<?>) obj;
        if (metadata == null) {
            if (other.metadata != null)
                return false;
        } else if (!metadata.equals(other.metadata))
            return false;

        return true;
    }

}
