001/**
002 * Copyright 2013 John Ericksen
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *    http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016package org.androidtransfuse.gen.componentBuilder;
017
018import com.sun.codemodel.JBlock;
019import org.androidtransfuse.adapter.ASTMethod;
020import org.androidtransfuse.analysis.astAnalyzer.RegistrationAspect;
021import org.androidtransfuse.annotations.Factory;
022import org.androidtransfuse.experiment.*;
023import org.androidtransfuse.model.InjectionNode;
024import org.androidtransfuse.model.MethodDescriptor;
025import org.androidtransfuse.model.TypedExpression;
026
027import javax.inject.Inject;
028import java.util.Map;
029
030/**
031 * @author John Ericksen
032 */
033public class ListenerRegistrationGenerator implements Generation {
034
035    private final ASTMethod creationMethod;
036
037    @Inject
038    public ListenerRegistrationGenerator(/*@Assisted*/ASTMethod creationMethod) {
039        this.creationMethod = creationMethod;
040    }
041
042    @Factory
043    public interface ListerRegistrationGeneratorFactory {
044        ListenerRegistrationGenerator build(ASTMethod creationMethod);
045    }
046
047    @Override
048    public void schedule(final ComponentBuilder componentBuilder, ComponentDescriptor descriptor) {
049
050        componentBuilder.add(creationMethod, GenerationPhase.POSTINJECTION, new ComponentMethodGenerator() {
051            @Override
052            public void generate(MethodDescriptor methodDescriptor, JBlock block) {
053            //add listener registration
054            for (Map.Entry<InjectionNode, TypedExpression> injectionNodeJExpressionEntry : componentBuilder.getExpressionMap().entrySet()) {
055                if (injectionNodeJExpressionEntry.getKey().containsAspect(RegistrationAspect.class)) {
056                    RegistrationAspect registrationAspect = injectionNodeJExpressionEntry.getKey().getAspect(RegistrationAspect.class);
057
058                    for (RegistrationGenerator builder : registrationAspect.getRegistrationBuilders()) {
059                        builder.build(componentBuilder, creationMethod, injectionNodeJExpressionEntry.getValue());
060                    }
061                }
062            }
063            }
064        });
065    }
066}