package com.example.chatapp.activities

import android.annotation.SuppressLint
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.widget.TextView
import com.example.chatapp.ChatApplication
import com.example.chatapp.R
import com.example.chatapp.network.SocketClient
import java.util.concurrent.TimeUnit

class SplashScreenActivity : AppCompatActivity() {

    lateinit var connectInfo: TextView

    @SuppressLint("SetTextI18n")
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_splash_screen)

        connectInfo = findViewById(R.id.connectInfo)
        connectInfo.text = "Connexion en cours..."

        val connection = SocketClient()


        Thread {
            while (true) {
                System.out.println("Connexion en cours...")
                val address = ChatApplication.address
                val port = ChatApplication.port
                if (connection.Connection(address, port) == 0) {
                    if (connection.ping()) {
                        break
                    }
                }
                TimeUnit.SECONDS.sleep(1);
            }
            connection.Disconnect()
            connectInfo.text = "Connexion réussie"

            Handler(Looper.getMainLooper()).postDelayed({
                Intent(this, AuthentificationActivity::class.java).also {
                    startActivity(it)
                }
                finish()
            }, 1000)
        }.start()

    }
}