package com.example.cmpt362_group30_maze_game.leaderboard

import androidx.lifecycle.LiveData
import androidx.lifecycle.ViewModel
import com.google.firebase.Firebase
import com.google.firebase.firestore.FirebaseFirestore
import com.google.firebase.firestore.firestore
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.launch

class LeaderboardViewModel: ViewModel() {
    private val db: FirebaseFirestore = Firebase.firestore

    companion object {
        const val COLLECTION_NAME = "user_runs"
        const val USERNAME = "username"
        const val TIME = "time"
        const val DIFFICULTY = "difficulty"
    }

    // Updates the LiveData variable to follow top ten entries on the specified map difficulty
    fun queryTopTenByDifficulty(difficulty: Int): LiveData<List<LeaderboardEntry>> {
        val query  = db.collection(COLLECTION_NAME).orderBy(TIME).limit(10).whereEqualTo(DIFFICULTY, difficulty)
        return LeaderboardEntryLiveData(query)
    }

    // Inserts a new run into the database with the given arguments
    fun insertNewRun(playerName: String, time: Int, difficulty: Int) {
        val newRun = hashMapOf(
            USERNAME to playerName,
            TIME to time,
            DIFFICULTY to difficulty
        )

        CoroutineScope(IO).launch {
            db.collection(COLLECTION_NAME).add(newRun)
        }
    }
}