lebonprix.apk/java/io/xdrm/lebonprix/api/CategoryFetcher.kt

67 lines
1.9 KiB
Kotlin

package io.xdrm.lebonprix.api
import android.app.Activity
import android.app.AlertDialog
import android.app.Dialog
import android.content.Context
import android.content.DialogInterface
import android.graphics.Color
import android.support.v4.content.res.ResourcesCompat
import android.util.Log
import android.widget.ImageView
import android.widget.TextView
import android.widget.Toast
import io.xdrm.lebonprix.HomeActivity
import io.xdrm.lebonprix.R
import io.xdrm.lebonprix.anim.UnderlineAnimation
import io.xdrm.lebonprix.extensions.await
import kotlinx.android.synthetic.main.activity_home.*
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONArray
import java.net.URLEncoder
class CategoryFetcher(
var act: Activity,
val anim_target: ImageView,
val anim: UnderlineAnimation,
val httpClient: OkHttpClient
) {
suspend fun fetch(keywords: String) : JSONArray {
if( keywords.isEmpty() )
return JSONArray("[]")
GlobalScope.launch(Dispatchers.Main){ anim.animate(0F,0.5F).during(500).start() }
// 1. Prepare URL
val url = "https://www.lebonprix.info/api/categorizer?q=${ URLEncoder.encode(keywords, "UTF-8") }"
Log.i("API-Request", url)
// 2. Get response
return try{
httpClient.newCall( Request.Builder().url(url).build() )
.await()
.body()
?.string()
.let{ raw -> JSONArray(raw) }
}catch(e: Exception){
if( e !is CancellationException) {
act.runOnUiThread {
Toast.makeText(act.applicationContext, "Erreur: impossible de récupérer les catégories", Toast.LENGTH_LONG).show()
}
}
return JSONArray("[]")
}
}
}