using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class Leaderboard : MonoBehaviour
{
    public GameObject rowPrefab;
    public Transform itemsParent;
    
    public void Show(){
        gameObject.SetActive(true);


        StartCoroutine(show());
    }


    IEnumerator show(){
        WWW req = new WWW(DataManager.API_Endpoint +"get_leaderboard.php");
        yield return req;

        Debug.Log("Leaderboard: " + req.text);

        if(req.text.Contains("<td>") && req.text.Contains("<tr>")){

            string[] col = {"<td>"};
            string[] row = {"<tr>"};

            string[] columns = req.text.Split(col,System.StringSplitOptions.RemoveEmptyEntries);
            //Purge
            for(int i=0; i < itemsParent.childCount; i++){
                if(itemsParent.GetChild(i).gameObject != rowPrefab){
                    Destroy(itemsParent.GetChild(i).gameObject);
                }else{

                }
            }

            rowPrefab.SetActive(true);
            for (int i =0; i < columns.Length; i++)
            {
                string column = columns[i];
                string[] rows = column.Split(row, System.StringSplitOptions.RemoveEmptyEntries);

                if(rows.Length < 2){
                    Debug.Log("Error");
                }


                GameObject newRow = Instantiate(rowPrefab, itemsParent);
                newRow.transform.GetChild(0).GetComponent<Text>().text = $"{i+1}. {rows[0]}";
                newRow.transform.GetChild(1).GetComponent<Text>().text =rows[1] + " m";
            }
            rowPrefab.SetActive(false);
        }
    }
}
