package com.example.mathseduc

import android.content.Intent
import android.os.Bundle
import android.widget.*
import androidx.appcompat.app.AppCompatActivity
import com.example.mathseduc.controllers.ControllerChapter
import com.example.mathseduc.controllers.ControllerLobby
import com.example.mathseduc.controllers.ControllerUtiliser
import okhttp3.MultipartBody
import org.json.JSONObject


class CreateLobbyActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_create_lobby)

        var spinnerChapter = findViewById<Spinner>(R.id.spinnerChapter)

        // Fetch chapters from API
        val chaptersFromApi = ControllerChapter.getChapters()

        // Populate Spinner with fetched chapters
        if (chaptersFromApi != null) {
            val chapterNames = chaptersFromApi.map { it.name }.toTypedArray()

            val adapter = ArrayAdapter(this, android.R.layout.simple_spinner_item, chapterNames)
            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item)
            spinnerChapter.adapter = adapter
        }

        val buttonCreateLobby = findViewById<Button>(R.id.buttonCreateLobby)
        buttonCreateLobby.setOnClickListener {
            val lobbyName = findViewById<EditText>(R.id.editTextLobbyName).text.toString()
            val password = findViewById<EditText>(R.id.editTextPassword).text.toString()
            val nbPlayers = findViewById<EditText>(R.id.editTextNbPlayers).text.toString()
            val difficulty = findViewById<Spinner>(R.id.spinnerDifficulty).selectedItemPosition + 1
            val selectedChapterPosition = findViewById<Spinner>(R.id.spinnerChapter).selectedItemPosition
            val idChapter = chaptersFromApi?.getOrNull(selectedChapterPosition)?.id?: -1

            if (lobbyName.isNullOrBlank() || password.isNullOrBlank() || nbPlayers.isNullOrBlank() || nbPlayers.toInt() <= 0) {
                Toast.makeText(this, "Échec de la création du lobby. Veuillez réessayer.", Toast.LENGTH_SHORT).show()
            }
            else
            {
                // Create form data
                val formDataBuilder = MultipartBody.Builder().setType(MultipartBody.FORM)

                // Add fields to form data
                formDataBuilder.addFormDataPart("name", lobbyName)
                formDataBuilder.addFormDataPart("password", password)
                formDataBuilder.addFormDataPart("nbplayers", nbPlayers.toString())
                formDataBuilder.addFormDataPart("idplayercreator", MainActivity.idPlayerConnected.toString())
                formDataBuilder.addFormDataPart("idchapter", idChapter.toString())
                formDataBuilder.addFormDataPart("difficulty", difficulty.toString())

                // Appeler la fonction pour créer le lobby
                val idLobbyCreatedSuccessfully = ControllerLobby.createLobby(formDataBuilder)

                // Vérifier si la création du lobby a réussi
                if (idLobbyCreatedSuccessfully != -1) {
                    val intent = Intent(this, ServerDetailsActivity::class.java)
                    intent.putExtra("serverName", lobbyName)
                    intent.putExtra("lobbyId", idLobbyCreatedSuccessfully.toString())

                    val formDataBuilder = MultipartBody.Builder().setType(MultipartBody.FORM)
                    formDataBuilder.addFormDataPart("idplayer", MainActivity.idPlayerConnected.toString())
                    formDataBuilder.addFormDataPart("idlobby", idLobbyCreatedSuccessfully.toString())
                    formDataBuilder.addFormDataPart("playertime", "0")

                    ControllerUtiliser.createUtiliserByIdLobby(formDataBuilder)
                    startActivity(intent)
                } else {
                    Toast.makeText(this, "Échec de la création du lobby. Veuillez réessayer.", Toast.LENGTH_SHORT).show()
                }
            }
        }
    }
}