package com.example.pantallacompra

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.google.firebase.database.DataSnapshot
import com.google.firebase.database.DatabaseError
import com.google.firebase.database.DatabaseReference
import com.google.firebase.database.FirebaseDatabase
import com.google.firebase.database.ValueEventListener

class EventList : AppCompatActivity() {
    private lateinit var dbreference : DatabaseReference
    private lateinit var recycleView: RecyclerView
    private lateinit var eventList : ArrayList<Event>
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_event_list)

        recycleView = findViewById(R.id.eventRecycleView)
        recycleView.layoutManager = LinearLayoutManager(this)
        recycleView.setHasFixedSize(true)

        eventList = arrayListOf<Event>()
        getEvents()
    }

    private fun getEvents(){
        dbreference= FirebaseDatabase.getInstance().getReference("Eventos")
        dbreference.addValueEventListener(object : ValueEventListener {
            override fun onDataChange(snapshot: DataSnapshot) {
                if(snapshot.exists()){
                    for(event in snapshot.children){
                        val item=event.getValue(Event::class.java)
                        eventList.add(item!!)
                    }
                    //recycleView.adapter=MyAdapter(eventList)
                    var adapter=MyAdapter(eventList, this@EventList)
                    recycleView.adapter=adapter
                    adapter.setOnItemClickListener(object : MyAdapter.onItemClickListener{
                        override fun onItemClick(position: Int) {
                            //Toast.makeText(this@EventList,"${eventList[position].nombre.toString()}", Toast.LENGTH_LONG).show()
                            val nombreEvento: String= eventList[position].nombre.toString()
                            var salaEvento:String?=null
                            when(nombreEvento){
                                "Champions"-> salaEvento = "1"
                                "Los caligaris"->salaEvento="2"
                            }
                            val intent = Intent(this@EventList, ChairList::class.java)
                            intent.putExtra("nombreEvento",nombreEvento)//CLAVE : VALOR
                            intent.putExtra("sala",salaEvento)
                            startActivity(intent)
                        }

                    })

                }
            }

            override fun onCancelled(error: DatabaseError) {
                TODO("Not yet implemented")
            }

        })
    }
}