package com.example.cmpt362_group30_maze_game

import android.content.Context
import android.graphics.Color
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.BaseAdapter
import android.widget.TextView
import com.example.cmpt362_group30_maze_game.leaderboard.LeaderboardEntry
import java.util.Locale

class LeaderboardAdapter(private val context: Context, private var dataSource: List<LeaderboardEntry>) : BaseAdapter() {

    private val inflater: LayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

    //  helper function to update data without recreating the adapter
    fun replaceData(newDetails: List<LeaderboardEntry>) {
        dataSource = newDetails
        notifyDataSetChanged()
    }
    override fun getCount(): Int {
        return dataSource.size
    }
    override fun getItem(position: Int): Any {
        return dataSource[position]
    }
    override fun getItemId(position: Int): Long {
        return position.toLong()
    }

    override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View {
        val rowView = convertView ?: inflater.inflate(R.layout.item_leaderboard, parent, false)

        // Get the data item for this position
        val entry = getItem(position) as LeaderboardEntry

        // Get references to the TextViews
        val tvRank = rowView.findViewById<TextView>(R.id.tvRank)
        val tvName = rowView.findViewById<TextView>(R.id.tvPlayerName)
        val tvTime = rowView.findViewById<TextView>(R.id.tvTime)

        // Calculate Rank (list position + 1)
        tvRank.text = (position + 1).toString()
        tvName.text = entry.username

        //Format time to minutes and seconds
        val minutes = entry.time / 60
        val seconds = entry.time % 60
        tvTime.text = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds)


        // Optional: Alternate row colors for readability
        if (position % 2 == 1) {
            rowView.setBackgroundColor(android.graphics.Color.parseColor("#FAFAFA"))
        } else {
            rowView.setBackgroundColor(android.graphics.Color.WHITE)
        }

        return rowView
    }
}