using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Leaderboard : MonoBehaviour
{
    public Text[] leaderboardItems;
    public float updateInterval = 0.5f;
    float t;
    void Start()
    {
        RefreshLeaderboard();
    }

    // Update is called once per frame
    void Update()
    {
        if (t < updateInterval)
        {
            t += Time.deltaTime;
        }
        else
        {
            RefreshLeaderboard();
            t = 0;
        }
    }

    public void RefreshLeaderboard()
    {
        SpaceshipController[] players = FindObjectsOfType<SpaceshipController>();
        //Simple bubble sort to sort players by score
        SpaceshipController temp;
        for (int j = 0; j <= players.Length - 2; j++)
        {
            for (int i = 0; i <= players.Length - 2; i++)
            {
                if (players[i].Scores > players[i + 1].Scores)
                {
                    temp = players[i + 1];
                    players[i + 1] = players[i];
                    players[i] = temp;
                }
            }
        }
        //Populate leaderboard
        for(int i =0; i < leaderboardItems.Length; i++){
            if(i < players.Length){
                SpaceshipController thisPlayer = players[players.Length-i-1];
                leaderboardItems[i].gameObject.SetActive(true);
                leaderboardItems[i].text = (i+1) + ". " +thisPlayer.pname;
                leaderboardItems[i].transform.GetChild(0).GetComponent<Text>().text = thisPlayer.Scores.ToString();
            }else{
                leaderboardItems[i].gameObject.SetActive(false);
            }
        }
    }
}
