package com.example.chatapp.activities

import android.annotation.SuppressLint
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.Menu
import android.view.MenuItem
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.chatapp.R
import com.example.chatapp.adapters.ConvRecyclerAdapter
import com.example.chatapp.models.Conv
import com.example.chatapp.network.SocketClient
import com.google.android.material.floatingactionbutton.FloatingActionButton
import java.io.IOException

class HomeActivity : AppCompatActivity() {

    lateinit var rvConv: RecyclerView
    lateinit var fabChat: FloatingActionButton
    lateinit var convRecyclerAdapter: ConvRecyclerAdapter

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

        rvConv = findViewById(R.id.rvConv)
        fabChat = findViewById(R.id.fabChat)

        fabChat.setOnClickListener {

        }

        // val realConv: MutableList<Conv> = mutableListOf()

//        Thread {
//            val connection = SocketClient()
//
//            try {
//                // Récupération de Général
//                var response = connection.GeneralMessage()
//                println(response)
//                realConv.add(Conv("Général", response.last(), 1695738248))
//                runOnUiThread {
//                    convRecyclerAdapter = ConvRecyclerAdapter()
//                    convRecyclerAdapter.items = realConv
//                    rvConv.apply {
//                        layoutManager = LinearLayoutManager(this@HomeActivity)
//                        adapter = convRecyclerAdapter
//                    }
//                }
//            } catch (e: IOException) {
//                e.printStackTrace(System.out)
//            }
//        }

        // TODO Récupérer la liste des conversations

        val convs = mutableListOf(
            Conv("Hyperion", "Hey", 1695738248),
            Conv("Dalh", "Mouais", 1695738248),
            Conv("Atlas", "Ben voyons", 1695738248),
        )
        convRecyclerAdapter = ConvRecyclerAdapter()
        convRecyclerAdapter.items = convs
        rvConv.apply {
            layoutManager = LinearLayoutManager(this@HomeActivity)
            adapter = convRecyclerAdapter
        }
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(R.menu.menu_home, menu)
        return super.onCreateOptionsMenu(menu)
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == R.id.itemLogout) {
            // TODO Logout
            finish()
            Intent(this, AuthentificationActivity::class.java).also {
                startActivity(it)
            }
        }
        return super.onOptionsItemSelected(item)
    }
}