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.variableBuilder.resource;
017
018import com.sun.codemodel.JExpression;
019import com.sun.codemodel.JInvocation;
020import org.androidtransfuse.adapter.ASTType;
021import org.androidtransfuse.gen.InjectionBuilderContext;
022import org.androidtransfuse.gen.InjectionExpressionBuilder;
023import org.androidtransfuse.gen.variableDecorator.TypedExpressionFactory;
024import org.androidtransfuse.model.InjectionNode;
025import org.androidtransfuse.model.TypedExpression;
026
027import javax.inject.Inject;
028
029public class MethodBasedResourceExpressionBuilder implements ResourceExpressionBuilder {
030
031    private final ASTType returnType;
032    private final String accessMethod;
033    private final InjectionNode resourcesInjectionNode;
034    private final InjectionExpressionBuilder injectionExpressionBuilder;
035    private final TypedExpressionFactory typedExpressionFactory;
036
037    @Inject
038    public MethodBasedResourceExpressionBuilder(/*@Assisted*/ ASTType returnType,
039                                                /*@Assisted*/ String accessMethod,
040                                                /*@Assisted*/ InjectionNode resourcesInjectionNode,
041                                                InjectionExpressionBuilder injectionExpressionBuilder,
042                                                TypedExpressionFactory typedExpressionFactory) {
043        this.returnType = returnType;
044        this.accessMethod = accessMethod;
045        this.resourcesInjectionNode = resourcesInjectionNode;
046        this.injectionExpressionBuilder = injectionExpressionBuilder;
047        this.typedExpressionFactory = typedExpressionFactory;
048    }
049
050    @Override
051    public TypedExpression buildExpression(InjectionBuilderContext context, JExpression resourceIdExpr) {
052        TypedExpression resourcesVar = injectionExpressionBuilder.buildVariable(context, resourcesInjectionNode);
053
054        JInvocation expression = resourcesVar.getExpression().invoke(accessMethod).arg(resourceIdExpr);
055
056        return typedExpressionFactory.build(returnType, expression);
057    }
058}