/*
 * 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.parsing.asm;

import static java.lang.String.format;
import static org.springframework.config.java.internal.parsing.asm.AsmUtils.newClassReader;
import static org.springframework.util.ClassUtils.convertClassNameToResourcePath;

import java.util.ArrayList;
import org.springframework.asm.AnnotationVisitor;
import org.springframework.asm.ClassReader;
import org.springframework.asm.Type;
import org.springframework.config.java.internal.model.ConfigurationClass;
import org.springframework.config.java.internal.model.ConfigurationModel;
import org.springframework.util.Assert;


/** TODO: JAVADOC */
class ImportAnnotationVisitor extends AnnotationAdapter {
    private final ArrayList<String> classesToImport = new ArrayList<String>();
    private final ConfigurationClass importingClass;
    private final ConfigurationModel model;

    public ImportAnnotationVisitor(ConfigurationClass importingClass, ConfigurationModel model) {
        super(AsmUtils.EMPTY_VISITOR);

        this.importingClass = importingClass;
        this.model = model;
    }

    @Override
    public AnnotationVisitor visitArray(String attribName) {
        Assert.isTrue("value".equals(attribName),
                      format("expected 'value' attribute, got unknown '%s' attribute", attribName));

        return new AnnotationAdapter(AsmUtils.EMPTY_VISITOR) {
            @Override
            public void visit(String na, Object type) {
                Assert.isInstanceOf(Type.class, type);
                classesToImport.add(((Type) type).getClassName());
            }
        };
    }

    @Override
    public void visitEnd() {
        for(String classToImport : classesToImport)
            processClassToImport(classToImport);

        ImportStackHolder.getImportStack().pop();
    }

    private void processClassToImport(String classToImport) {
        ConfigurationClass configClass = new ConfigurationClass();

        ConfigurationClassVisitor configClassVisitor =
            new ConfigurationClassVisitor(configClass, model);

        ClassReader reader = newClassReader(convertClassNameToResourcePath(classToImport));
        reader.accept(configClassVisitor, false);

        importingClass.addImportedClass(configClass);
    }

}
