1/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16package android.arch.persistence.room.processor
17
18import android.arch.persistence.room.vo.Entity
19import android.arch.persistence.room.vo.ShortcutQueryParameter
20import com.google.auto.common.MoreElements
21import com.google.auto.common.MoreTypes
22import javax.lang.model.element.AnnotationMirror
23import javax.lang.model.element.ExecutableElement
24import javax.lang.model.type.DeclaredType
25import javax.lang.model.type.TypeMirror
26import kotlin.reflect.KClass
27
28/**
29 * Common functionality for shortcut method processors
30 */
31class ShortcutMethodProcessor(baseContext : Context,
32                              val containing: DeclaredType,
33                              val executableElement: ExecutableElement) {
34    val context = baseContext.fork(executableElement)
35    private val asMember = context.processingEnv.typeUtils.asMemberOf(containing, executableElement)
36    private val executableType = MoreTypes.asExecutable(asMember)
37
38    fun extractAnnotation(klass : KClass<out Annotation>,
39                          errorMsg : String) : AnnotationMirror? {
40        val annotation = MoreElements.getAnnotationMirror(executableElement,
41                klass.java).orNull()
42        context.checker.check(annotation != null, executableElement, errorMsg)
43        return annotation
44    }
45
46    fun extractReturnType() : TypeMirror {
47        return executableType.returnType
48    }
49
50    fun extractParams(missingParamError: String)
51            : Pair<Map<String, Entity>, List<ShortcutQueryParameter>> {
52        val params = executableElement.parameters
53                .map { ShortcutParameterProcessor(
54                        baseContext = context,
55                        containing = containing,
56                        element = it).process() }
57        context.checker.check(params.isNotEmpty(), executableElement, missingParamError)
58        val entities = params
59                .filter { it.entityType != null }
60                .associateBy({ it.name }, {
61                    EntityProcessor(
62                            baseContext = context,
63                            element = MoreTypes.asTypeElement(it.entityType)).process()
64                })
65        return Pair(entities, params)
66    }
67}
68