package com.example.mathseduc.controllers

import android.os.StrictMode
import com.example.mathseduc.models.Chapter
import com.example.mathseduc.models.Lobby
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import okhttp3.OkHttpClient
import okhttp3.Request
import java.io.IOException

class ControllerChapter {
    companion object {
        fun getChapters(): ArrayList<Chapter>? {

            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/chapters/qUOGkWdoPCgbmuqxIC8xiaX0rV1Pw1LoPafkaoHOgszEyD9P2vcOu493xCDZpAqO/1")
                .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<Chapter>>() {}.type

                // Parse API response and return the list of chapters
                return gson.fromJson(response.body!!.string(), typeTokenProduct)

            }

            return null
        }
    }
}