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

using UnityEngine.Networking;

public class PointCounter : MonoBehaviour
{
    public Text total;
    
    public List<Text> players;
    
    private string serverUrl;

    public GameObject serverManager;

    private float period = 0.0f;

    // Start is called before the first frame update
    void Start()
    {
        serverUrl = "https://smarthubs.media.tuwien.ac.at/api/get_all_player_points/";
    }

    // Update is called once per frame
    

    void Update()
    {
        if (period > 4.0f)
        {
            //Do Stuff
            string currentGame = serverManager.GetComponent<CurrentGameConnect>().GetGameNumber();
            
            Debug.Log(currentGame);

            string url = serverUrl + currentGame.ToString();

            if(currentGame != "0"){
                Debug.Log(url);
                StartCoroutine(getValues(url)); 
            }

            period = 0;
        }

        period += UnityEngine.Time.deltaTime;
    }

    public IEnumerator getValues(string newServerUrl)
    {
        UnityWebRequest www = UnityWebRequest.Get(newServerUrl);

        yield return www.SendWebRequest();

        if (www.result != UnityWebRequest.Result.Success)
        {
            Debug.Log(www.error);
        }
        else
        {

          // Show results as text
            //Debug.Log(www.downloadHandler.text);
            string playerPoints = www.downloadHandler.text;

            var result = playerPoints.Split(new[] { ',' })
                                .Select(s => s.Split(new[] { ':' }))
                                .ToDictionary(k => k[0].Replace("\"", "").Replace("}", "").Replace("{", "").Trim(), v => v[1].Replace("\"", "").Replace("}", "").Trim());

            int i = 0;
            int res = 0;
            foreach (KeyValuePair<string, string> entry in result)
            {
                players[i].text = entry.Value;
                res += int.Parse(entry.Value);
                i++;

                Debug.Log("the result is: " + result);
            }

            total.text = res.ToString();

        }

    }
}