package com.example.cmpt362_group30_maze_game.leaderboard

import android.util.Log
import androidx.lifecycle.LiveData
import com.google.firebase.firestore.ListenerRegistration
import com.google.firebase.firestore.Query

// this class creates a LiveData list by adding a snapshot listener to a specified query on the firestore database
class LeaderboardEntryLiveData(private val query: Query) : LiveData<List<LeaderboardEntry>>() {
    private var listenerRegistration: ListenerRegistration? = null

    override fun onActive() {
        super.onActive()

        listenerRegistration = query.addSnapshotListener { snapshot, error ->
            if (error != null) {
                Log.w("FirestoreLiveData", "Listen failed.", error)
                return@addSnapshotListener
            }

            val entries = snapshot?.toObjects(LeaderboardEntry::class.java)
            value = entries ?: emptyList()
        }
    }

    override fun onInactive() {
        super.onInactive()
        listenerRegistration?.remove()
    }
}