package com.example.mathseduc.controllers

import android.os.StrictMode
import android.util.Log
import com.example.mathseduc.models.Lobby
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import org.json.JSONObject
import java.io.IOException


class ControllerLobby {
    companion object {
        fun getLobbies(): ArrayList<Lobby>? {

            val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
            StrictMode.setThreadPolicy(policy)

            // Client HTTP API
            val client = OkHttpClient()

            // API Access
            val request = Request.Builder()
                .url("https://trusting-panini.87-106-126-109.plesk.page/api/all/lobbies/qUOGkWdoPCgbmuqxIC8xiaX0rV1Pw1LoPafkaoHOgszEyD9P2vcOu493xCDZpAqO")
                .build()

            // API Response
            client.newCall(request).execute().use { response ->
                if (!response.isSuccessful) throw IOException("Unexpected code $response")

                // Gson deserialization
                val gson = Gson()
                val typeTokenProduct = object : TypeToken<ArrayList<Lobby>>() {}.type

                return gson.fromJson(response.body!!.string(), typeTokenProduct)
            }
            return null
        }

        fun createLobby(lobbyData: MultipartBody.Builder): Int {
            try {
                val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
                StrictMode.setThreadPolicy(policy)

                // Client HTTP API
                val client = OkHttpClient()

                // API Access
                val request = Request.Builder()
                    .url("https://trusting-panini.87-106-126-109.plesk.page/api/add/lobbies/qUOGkWdoPCgbmuqxIC8xiaX0rV1Pw1LoPafkaoHOgszEyD9P2vcOu493xCDZpAqO")
                    .post(lobbyData.build())
                    .build()

                // API Response
                client.newCall(request).execute().use { response ->
                    if (response.isSuccessful) {
                        // Si la réponse est réussie, extraire l'ID du lobby du corps de la réponse JSON
                        val responseBody = response.body?.string()
                        val jsonObject = JSONObject(responseBody)

                        // Retourner l'ID du lobby
                        return jsonObject.optInt("lobby_id", -1)
                    }
                }
            } catch (e: Exception) {
                // Log en cas d'erreur
                Log.e("CreateLobby", "Error creating lobby", e)
            }
            return -1
        }
    }
}