1/*
2 * Copyright (C) 2017 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 */
16
17package androidx.room.solver.types
18
19import androidx.room.ext.L
20import androidx.room.ext.N
21import androidx.room.ext.T
22import androidx.room.solver.CodeGenScope
23import androidx.room.vo.CustomTypeConverter
24import androidx.room.writer.ClassWriter
25import com.squareup.javapoet.ClassName
26import com.squareup.javapoet.FieldSpec
27import javax.lang.model.element.Modifier
28
29/**
30 * Wraps a type converter specified by the developer and forwards calls to it.
31 */
32class CustomTypeConverterWrapper(val custom: CustomTypeConverter)
33    : TypeConverter(custom.from, custom.to) {
34
35    override fun convert(inputVarName: String, outputVarName: String, scope: CodeGenScope) {
36        scope.builder().apply {
37            if (custom.isStatic) {
38                addStatement("$L = $T.$L($L)",
39                        outputVarName, custom.typeName,
40                        custom.methodName, inputVarName)
41            } else {
42                addStatement("$L = $N.$L($L)",
43                        outputVarName, typeConverter(scope),
44                        custom.methodName, inputVarName)
45            }
46        }
47    }
48
49    fun typeConverter(scope: CodeGenScope): FieldSpec {
50        val baseName = (custom.typeName as ClassName).simpleName().decapitalize()
51        return scope.writer.getOrCreateField(object : ClassWriter.SharedFieldSpec(
52                baseName, custom.typeName) {
53            override fun getUniqueKey(): String {
54                return "converter_${custom.typeName}"
55            }
56
57            override fun prepare(writer: ClassWriter, builder: FieldSpec.Builder) {
58                builder.addModifiers(Modifier.PRIVATE)
59                builder.addModifiers(Modifier.FINAL)
60                builder.initializer("new $T()", custom.typeName)
61            }
62        })
63    }
64}
65