package com.trace.drawing.people.up

import AESUtils
import android.app.Activity
import android.util.Log
import android.widget.Toast
import com.trace.drawing.people.tools.App
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.Call
import okhttp3.Callback
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.logging.HttpLoggingInterceptor
import org.json.JSONObject
import java.io.IOException


object Http {
    val aesKey = "e67cbcee5e573d1b"
    val url = "http://mobile-server.lux-ad.com:58077/api/mobile/save"


    fun makeGetRequest(context: Activity) {
        val logging = HttpLoggingInterceptor()
        logging.setLevel(HttpLoggingInterceptor.Level.BODY)



        GlobalScope.launch(Dispatchers.IO) {
            val data = Upload.getData(context)

            withContext(Dispatchers.Main){
                val encryptJson = AESUtils.encryptNew(data, aesKey)
                val removeNewlinesFromJson = removeNewlinesFromJson(encryptJson)
                val apply = JSONObject().apply {
                    put("encrypted", removeNewlinesFromJson)
                }
                val client: OkHttpClient = OkHttpClient.Builder()
                    .addInterceptor(logging)
                    .build()
//        val client = OkHttpClient()
                val requestBody: RequestBody =
                    apply.toString().toRequestBody("application/json; charset=utf-8".toMediaType())

                val request: Request = Request.Builder()
                    .url(url)
                    .post(requestBody)
                    .build()
                client.newCall(request).enqueue(object : Callback {
                    override fun onFailure(call: Call, e: IOException) {
                        Log.e("==================", "onFailure  e=${e.message}")
                    }

                    override fun onResponse(call: Call, response: Response) {
                        Log.e("==================", "response=${response.code}  ${response.message}")
                    }

                })
            }

        }


    }
    fun removeNewlinesFromJson(jsonString: String): String {
        return jsonString.replace("\n", "").replace("\r", "")
    }
}