package melody.offline.music.http

import okhttp3.Call
import okhttp3.Callback
import okhttp3.Response
import org.json.JSONObject
import melody.offline.music.App
import melody.offline.music.sp.AppStore
import melody.offline.music.util.AesEncryptUtil
import melody.offline.music.util.LogTag
import java.io.IOException

class CommonIpInfoUtil {

    private val TAG = LogTag.VO_API_LOG

    companion object {
        val shared: CommonIpInfoUtil by lazy { CommonIpInfoUtil() }
    }

    fun initIPInfo() {
        try {
            MyHttpUtil.mInstance.getIPInfo(
                object : Callback {
                    override fun onFailure(call: Call, e: IOException) {

                    }

                    override fun onResponse(call: Call, response: Response) {
                        try {
                            LogTag.LogD(TAG, "getIPInfo response->${response}")
                            if (response.code == 200) {
                                val responseData = response.body?.string()
                                if (responseData != null) {
                                    val jsonObject = JSONObject(responseData)
                                    val status = jsonObject.optString("status")
                                    if (status == "Success") {
                                        val data = jsonObject.optString("data")
                                        val decryptData = AesEncryptUtil.desEncrypt(data)
                                        val jsonObjectDecryptData = JSONObject(decryptData)
                                        LogTag.LogD(TAG, "getIPInfo data->${jsonObjectDecryptData}")
                                        val isoCode = jsonObjectDecryptData.optString("isoCode")
                                        AppStore(App.app).ipCountryCode = isoCode
                                    }
                                }
                            }
                        } catch (e: Exception) {
                            e.printStackTrace()
                        }
                    }
                }
            )
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }
}