package but.androidstudio.tetris

import adaptator.RecyclerViewAdaptator
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import api.TetrisClient
import api.User
import okhttp3.OkHttpClient
import java.io.InputStream
import java.security.KeyStore
import java.security.SecureRandom
import java.security.cert.CertificateFactory
import javax.net.ssl.SSLContext
import javax.net.ssl.TrustManagerFactory
import javax.net.ssl.X509TrustManager


class InfoUserFragment : Fragment() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var adaptator: RecyclerViewAdaptator
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        val view = inflater.inflate(R.layout.fragment_info_user, container, false)
        // Set up RecyclerView
        recyclerView = view.findViewById<RecyclerView>(R.id.tableUser)
        recyclerView.layoutManager = LinearLayoutManager(requireContext())
        adaptator =RecyclerViewAdaptator(listOf())
        recyclerView.adapter = adaptator
        return view
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        val buttonBack: Button = view.findViewById(R.id.backButton)
        buttonBack.setOnClickListener {
            val fragmentManager = requireActivity().supportFragmentManager
            fragmentManager.beginTransaction()
                .replace(R.id.homeLayout, MainFragment())
                .commit()
        }

        // Read the SSL certificate for the request
        val certificateStream : InputStream = resources.openRawResource(R.raw.sni_cloudflaressl_com)

        // We create a certificateFactory to extract de data of the certificateInputStream
        val certificateFactory = CertificateFactory.getInstance("X.509")
        val certificate = certificateFactory.generateCertificate(certificateStream)

        //To specified the certificate to used
        val keyStore = KeyStore.getInstance(KeyStore.getDefaultType())
        keyStore.load(null, null)
        keyStore.setCertificateEntry("ca", certificate)
        val trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm())
        trustManagerFactory.init(keyStore)

        //To create a SSL context
        val sslContext = SSLContext.getInstance("SSL")
        sslContext.init(null, trustManagerFactory.trustManagers, SecureRandom())

        // We create a OkHttpClient to use the SSLContext
        val okHttpClient: OkHttpClient = OkHttpClient.Builder()
            .sslSocketFactory(sslContext.socketFactory, trustManagerFactory.trustManagers[0] as X509TrustManager)
            .build()

        val client = TetrisClient(okHttpClient)

        client.getUsers { users, error ->
            if (error != null) {
                // Handle error
                println("Error: ${error.message}")
            } else {
                // Handle success
                adaptator.userData = users!!
                recyclerView.adapter?.notifyDataSetChanged()
            }
        }
    }
}