package com.example.mathseduc.controllers

import android.os.StrictMode
import android.util.Log
import com.example.mathseduc.models.Lobby
import com.example.mathseduc.models.Utiliser
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.MultipartBody
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
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 getIdQuestionsLobby(idLobby: Int): ArrayList<String> {
            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/propose/$idLobby/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<Map<String, String>>>() {}.type

                val questionList: ArrayList<Map<String, String>> = gson.fromJson(response.body!!.string(), typeTokenProduct)

                // Extracting question IDs
                val idList = ArrayList<String>()
                for (question in questionList) {
                    val id = question["idquestion"]
                    if (id != null) {
                        idList.add(id)
                    }
                }

                return idList
            }
        }

        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
        }

        fun playerCreatorIdPresentInLobby(idPlayer: Int, lobbyId: Int): Boolean {

            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/lobbies/$lobbyId/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

                val lobby: ArrayList<Lobby> = gson.fromJson(response.body!!.string(), typeTokenProduct)
                return lobby[0].idplayercreator == idPlayer
            }
            return false
        }

        fun deleteLobby(lobbyId: Int) {
            try {
                val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
                StrictMode.setThreadPolicy(policy)

                // Client HTTP API
                val client = OkHttpClient()

                // API Access - Suppression du lobby
                val deleteRequest = Request.Builder()
                    .url("https://trusting-panini.87-106-126-109.plesk.page/api/lobbies/$lobbyId/qUOGkWdoPCgbmuqxIC8xiaX0rV1Pw1LoPafkaoHOgszEyD9P2vcOu493xCDZpAqO")
                    .delete()
                    .build()

                // API Response
                val deleteResponse: Response = client.newCall(deleteRequest).execute()

                // Vérifier si la suppression a réussi
                if (!deleteResponse.isSuccessful) {
                    Log.e("deleteLobby", "Error deleting lobby")
                }
            } catch (e: Exception) {
                // Log en cas d'erreur
                Log.e("deleteLobby", "Error deleting lobby", e)
            }
        }

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

                // Client HTTP API
                val client = OkHttpClient()

                // API Access - Mise à jour du lobby
                val updateRequest = Request.Builder()
                    .url("https://trusting-panini.87-106-126-109.plesk.page/api/update/lobbies/idplayercreator/$lobbyId/qUOGkWdoPCgbmuqxIC8xiaX0rV1Pw1LoPafkaoHOgszEyD9P2vcOu493xCDZpAqO")
                    // Ajoutez d'autres paramètres ou données pour la mise à jour si nécessaire
                    .post(lobbyData.build()) //TODO attention api pb
                    .build()

                // API Response
                val updateResponse: Response = client.newCall(updateRequest).execute()

                // Vérifier si la mise à jour a réussi
                if (!updateResponse.isSuccessful) {
                    Log.e("updateLobby", "Error updating lobby")
                }
            } catch (e: Exception) {
                // Log en cas d'erreur
                Log.e("updateLobby", "Error updating lobby", e)
            }
        }

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

                // Client HTTP API
                val client = OkHttpClient()

                // API Access - Mise à jour du lobby
                val updateRequest = Request.Builder()
                    .url("https://trusting-panini.87-106-126-109.plesk.page/api/update/lobbies/launched/$lobbyId/qUOGkWdoPCgbmuqxIC8xiaX0rV1Pw1LoPafkaoHOgszEyD9P2vcOu493xCDZpAqO")
                    // Ajoutez d'autres paramètres ou données pour la mise à jour si nécessaire
                    .post(lobbyData.build()) //TODO attention api pb
                    .build()

                // API Response
                val updateResponse: Response = client.newCall(updateRequest).execute()

                // Vérifier si la mise à jour a réussi
                if (!updateResponse.isSuccessful) {
                    Log.e("updateLobby", "Error updating lobby")
                }
            } catch (e: Exception) {
                // Log en cas d'erreur
                Log.e("updateLobby", "Error updating lobby", e)
            }
        }

        fun getNbPlayerInLobby(lobbyId: Int): Int {

            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/utiliser/$lobbyId/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<Utiliser>>() {}.type

                val utiliser: ArrayList<Utiliser> = gson.fromJson(response.body!!.string(), typeTokenProduct)
                return utiliser.size
            }
            return -1
        }

        fun lobbyIsLaunched(lobbyId: Int): Boolean {

            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/lobbies/$lobbyId/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

                val lobby: ArrayList<Lobby> = gson.fromJson(response.body!!.string(), typeTokenProduct)
                return lobby[0].launched == 1
            }
            return false
        }
    }
}