package com.mybus17000.network



import okhttp3.Call
import okhttp3.Callback
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
import java.io.IOException
import java.util.concurrent.TimeUnit


private const val CONNECT_TIMEOUT = 15L
private const val READ_TIMEOUT = 15L
private const val WRITE_TIMEOUT = 15L


fun PlayActiveScenario(mUrlString: String, vCallback: DownloadCallback):String {

    var vRet: String = ""
    var mCallback: DownloadCallback = vCallback

    val client2 = OkHttpClient.Builder()
        .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
        .writeTimeout(WRITE_TIMEOUT, TimeUnit.SECONDS)
        .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
        .build()


    val request = Request.Builder()
        .url(mUrlString)
        .header("Accept", "application/json")
        .build()

    client2.newCall(request).enqueue(object : Callback {
        override fun onFailure(call: Call, e: IOException) {
            e.printStackTrace()
        }

        override fun onResponse(call: Call, response: Response) {
            response.use {
                if (!response.isSuccessful) {
                    vRet = "Unexpected code $response"
                } else {
                    for ((name, value) in response.headers) {
                        vRet += "$name: $value"
                    }

                    vRet = response.body!!.string()
                    mCallback.UpdateReponse(vRet)
                }
            }
        }
    })
    return vRet
}

