package com.epfl.esl.sportstracker

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
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 MyHistoryViewModel : ViewModel() {
    val database: FirebaseDatabase = FirebaseDatabase.getInstance()
    val profileRef: DatabaseReference = database.getReference("Profiles")
    private var _sessions = MutableLiveData<List<SessionItem>>(listOf())
    val sessions: LiveData<List<SessionItem>>
        get() = _sessions


    fun listenForHistory(username: String) {
        profileRef.addListenerForSingleValueEvent(object : ValueEventListener {
            override fun onDataChange(dataSnapshot: DataSnapshot) {
                val arrayList: ArrayList<SessionItem> = ArrayList()
                for (user in dataSnapshot.children) {
                    val userDatabase = user.child("username")
                        .getValue(String::class.java)
                    if (userDatabase != null && userDatabase == username) {
                        for (activityKey in user.children) {
                            for (activity in activityKey.children) {
                                val sessionItem = activity
                                    .getValue(SessionItem::class.java)
                                sessionItem?.let {
                                    arrayList.add(it)
                                }
                            }
                        }
                    }
                }
                _sessions.value = arrayList
            }
            override fun onCancelled(error: DatabaseError) {}
        })
    }

}
