package io.xdrm.lebonprix.api import android.app.Activity import android.app.AlertDialog import android.content.Context import android.widget.Toast import io.xdrm.lebonprix.HomeActivity import io.xdrm.lebonprix.extensions.await 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.JSONObject import java.net.URLEncoder class PricesFetcher( val act: Activity, val httpClient: OkHttpClient ) { private val specialCharMap = mapOf( Pair("&", " "), Pair("é", "e"), Pair("è", "e"), Pair("ê", "e"), Pair("î", "i"), Pair("ô", "o"), Pair("'", " "), Pair("-", " ")) suspend fun fetch(query: String, categories: Array): Array { val querySanitized = URLEncoder.encode(query, "utf-8") // query if( categories.isEmpty() ) return httpCall(querySanitized) val results = mutableListOf() categories.forEach { results.addAll(httpCall(querySanitized, it)) } return results.toTypedArray() } private fun sanitizeCategory(category: String) : String { return category.split("").map { if (it in specialCharMap.keys) specialCharMap[it] else it }.joinToString("") } suspend private fun httpCall(query: String, cat: String? = null): Array { var url = "http://www.lebonprix.info/api/sampling?q=$query" if( !cat.isNullOrBlank() ) url += "&c=${sanitizeCategory(cat)}" var error = false val result = try{ httpClient.newCall( Request.Builder().url(url).build() ) .await() .body() ?.string() .let{ JSONObject(it) } .getJSONArray("sample") .let{ arr -> Array( arr.length() ){ arr.getInt(it) } } }catch(e: Exception){ if( e !is CancellationException) { error = true act.runOnUiThread { Toast.makeText(act.applicationContext, "Erreur: impossible de récupérer les prix", Toast.LENGTH_LONG).show() } } return arrayOf() } // nothing found if( !error && result.isNullOrEmpty() ) act.runOnUiThread { Toast.makeText(act.applicationContext, "Aucun résultat", Toast.LENGTH_LONG).show() } return result } }