61 lines
1.7 KiB
Kotlin
61 lines
1.7 KiB
Kotlin
package it.danieleverducci.subitobeers
|
|
|
|
import android.util.Log
|
|
import android.widget.Toast
|
|
import it.danieleverducci.subitobeers.entities.Beer
|
|
import it.danieleverducci.subitobeers.networking.BeersFilter
|
|
import it.danieleverducci.subitobeers.networking.RetrofitProvider
|
|
import retrofit2.Call
|
|
import retrofit2.Callback
|
|
import retrofit2.Response
|
|
|
|
class BeersRepository {
|
|
|
|
companion object {
|
|
val TAG = "BeersRepository"
|
|
}
|
|
|
|
var listener: Listener? = null
|
|
var page = 1
|
|
var filter = BeersFilter()
|
|
private var more = true
|
|
|
|
/**
|
|
* Obtain a paginated list of beers from the server
|
|
* Use page property to set the page
|
|
*/
|
|
fun getBeers() {
|
|
// Obtain beers
|
|
val call = RetrofitProvider.getClient.getBeers(page, filter.brewedBefore, filter.brewedAfter)
|
|
call.enqueue(object: Callback<List<Beer>> {
|
|
override fun onResponse(call: Call<List<Beer>>, response: Response<List<Beer>>) {
|
|
if (response.body() != null) {
|
|
if (response.body()!!.isEmpty())
|
|
more = false
|
|
listener?.onBeersObtained(response.body()!!, more)
|
|
} else {
|
|
listener?.onFailure()
|
|
}
|
|
}
|
|
|
|
override fun onFailure(call: Call<List<Beer>>, t: Throwable) {
|
|
if (t.message != null)
|
|
Log.e(TAG, "Unable to obtain beers: ${t}")
|
|
listener?.onFailure()
|
|
}
|
|
})
|
|
}
|
|
|
|
/**
|
|
* Discard page and restarts from first
|
|
*/
|
|
fun reset() {
|
|
page = 1
|
|
more = true
|
|
}
|
|
|
|
interface Listener {
|
|
fun onBeersObtained(beers: List<Beer>, more: Boolean)
|
|
fun onFailure()
|
|
}
|
|
} |