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

namespace Assets.Scripts.API
{
	public class Server : MonoBehaviour
	{
		public static string HOST_PROD = "https://quantifly.plnech.fr";
		public static string HOST_DEV = "http://localhost:8990";

	    public ScoresRes Scores;

		public Server ()
		{
		}

	    public void Start()
	    {
	        GetScores();
	    }

		public void GetScores ()
		{
			StartCoroutine(GetScoresAsync());
			Debug.Log("Done.");
		}

		IEnumerator GetScoresAsync() {
			UnityWebRequest www = UnityWebRequest.Get(HOST_PROD + "/scores/");
			yield return www.Send();

			if (www.isError) {
				Debug.LogError ("Error:" + www.error);
			} else {
				Debug.Log ("Got response: " + www.downloadHandler.text);
				Scores = ScoresRes.CreateFromJson (www.downloadHandler.text);
				Debug.Log ("Got scores: " + Scores);
			}
		}

		[Serializable]
		public class ScoresRes {
			public string status;
			public Score[] scores;

			public ScoresRes() {}

		    public static ScoresRes CreateFromJson(string scoresJSON)
		    {
		        return JsonUtility.FromJson<ScoresRes>(scoresJSON);
		    }

		    public override string ToString()
		    {
		        var s = (from e in scores
		            where e != null
		            select e.ToString()).ToArray();
		        return "Status: " + status + "Scores:\n" + string.Join(",", s);
		    }
		}
	}
}

