package org.octopus.randomfacts.core.shared

import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.json.JSONObject
import java.net.HttpURLConnection
import java.net.URL

object HttpClient {
    suspend fun fetchFact(onResult: (String) -> Unit) {
        withContext(Dispatchers.IO) {
            try {
                val url = URL(Const.HTTP_URL_ENDPOINT)
                val connection = url.openConnection() as HttpURLConnection
                connection.requestMethod = "GET"
                connection.connect()
                val result = connection.inputStream.bufferedReader().use { it.readText() }
                connection.disconnect()
                val json = JSONObject(result)
                onResult(json.getString("text"))
            } catch (e: Exception) {
                Log.e("Octopus RandomFacts HTTPCallError", e.message ?: "")
                onResult(Const.HTTP_ERROR_MSG)
            }
        }
    }
}