Server.cs 1.68 KB
Newer Older
1 2
using System;
using UnityEngine;
3
using UnityEngine.Networking;
4 5
using System.Collections;
using System.Collections.Generic;
Naliwe GS committed
6
using System.Linq;
7 8 9

namespace Assets.Scripts.API
{
Naliwe GS committed
10
	public class Server : MonoBehaviour
11
	{
12
		public static string HOST_PROD = "https://quantifly.plnech.fr";
13
		public static string HOST_DEV = "http://localhost:8990";
14

Naliwe GS committed
15 16
	    public ScoresRes Scores;

17 18 19 20
		public Server ()
		{
		}

Naliwe GS committed
21 22 23 24 25
	    public void Start()
	    {
	        GetScores();
	    }

26
		public void GetScores()
27
		{
28 29 30 31
			StartCoroutine(GetScoresAsync());
		}

		IEnumerator GetScoresAsync() {
Naliwe GS committed
32
			UnityWebRequest www = UnityWebRequest.Get(HOST_PROD + "/scores/");
33
			yield return www.Send();
34 35

			if (www.isError) {
36 37 38
				Debug.LogError ("Error:" + www.error);
			} else {
				Debug.Log ("Got response: " + www.downloadHandler.text);
Naliwe GS committed
39 40
				Scores = ScoresRes.CreateFromJson (www.downloadHandler.text);
				Debug.Log ("Got scores: " + Scores);
41 42 43
			}
		}

PLN (Algolia) committed
44
		public static void PostScore(int score, String playerName, String playerTeam = null)
45 46 47 48 49
		{
			WWWForm form = new WWWForm();
			form.AddField("name", playerName);
			form.AddField("team", playerTeam);
			form.AddField("score", score);
50
			new WWW(HOST_PROD + "/score/", form);
51 52
		}

53
		[Serializable]
Naliwe GS committed
54
		public class ScoresRes {
55 56 57
			public string status;
			public Score[] scores;

58 59
			public ScoresRes() {}

60
		    public static ScoresRes CreateFromJson(string scoresJSON)
Naliwe GS committed
61
		    {
62
		        return JsonUtility.FromJson<ScoresRes>(scoresJSON);
Naliwe GS committed
63 64 65 66 67 68 69 70 71
		    }

		    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);
		    }
72 73 74 75
		}
	}
}