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 android.arch.persistence.room.solver.binderprovider
18
19import android.arch.persistence.room.ext.PagingTypeNames
20import android.arch.persistence.room.parser.ParsedQuery
21import android.arch.persistence.room.processor.Context
22import android.arch.persistence.room.solver.QueryResultBinderProvider
23import android.arch.persistence.room.solver.query.result.TiledDataSourceQueryResultBinder
24import android.arch.persistence.room.solver.query.result.ListQueryResultAdapter
25import android.arch.persistence.room.solver.query.result.LivePagedListQueryResultBinder
26import android.arch.persistence.room.solver.query.result.QueryResultBinder
27import javax.lang.model.type.DeclaredType
28import javax.lang.model.type.TypeMirror
29
30class LivePagedListQueryResultBinderProvider(val context: Context) : QueryResultBinderProvider {
31    private val livePagedListTypeMirror: TypeMirror? by lazy {
32        context.processingEnv.elementUtils
33                .getTypeElement(PagingTypeNames.LIVE_PAGED_LIST_PROVIDER.toString())?.asType()
34    }
35
36    override fun provide(declared: DeclaredType, query: ParsedQuery): QueryResultBinder {
37        val typeArg = declared.typeArguments[1]
38        val listAdapter = context.typeAdapterStore.findRowAdapter(typeArg, query)?.let {
39            ListQueryResultAdapter(it)
40        }
41        val countedBinder = TiledDataSourceQueryResultBinder(listAdapter,
42                query.tables.map { it.name })
43        return LivePagedListQueryResultBinder(countedBinder)
44    }
45
46    override fun matches(declared: DeclaredType): Boolean =
47            declared.typeArguments.size == 2 && isLivePagedList(declared)
48
49    private fun isLivePagedList(declared: DeclaredType): Boolean {
50        if (livePagedListTypeMirror == null) {
51            return false
52        }
53        val erasure = context.processingEnv.typeUtils.erasure(declared)
54        // we don't want to return paged list unless explicitly requested
55        return context.processingEnv.typeUtils.isAssignable(livePagedListTypeMirror, erasure)
56    }
57}