using System.Collections;
using TMPro;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.UI;

public class API : MonoBehaviour
{
	[SerializeField] private TextMeshProUGUI emailText;
	[SerializeField] private Toggle terms;
    [SerializeField] private ScoreBoard scoreBoard;

    public void PostStart()
    {
        AppData data = new AppData();
        data.meta = null;
        string json = JsonUtility.ToJson(data);

        StartCoroutine(PostRequest("https://interaktivno.go2digital.hr/api/games/tracking/", json));
    }

    public void PostEmail()
	{
        AppData data = new AppData();
        data.@event = "submit";
        data.meta = new Meta();
        data.meta.email = emailText.text;
        data.meta.customTerms = terms.isOn;
        data.meta.score = scoreBoard.Score;
        string json = JsonUtility.ToJson(data);

        StartCoroutine(PostRequest("https://interaktivno.go2digital.hr/api/games/tracking/", json));
	}


    IEnumerator PostRequest(string url, string json)
    {
        var uwr = new UnityWebRequest(url, "POST");
        byte[] jsonToSend = new System.Text.UTF8Encoding().GetBytes(json);
        uwr.uploadHandler = (UploadHandler)new UploadHandlerRaw(jsonToSend);
        uwr.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer();
        uwr.SetRequestHeader("Content-Type", "application/json");

        //Send the request then wait here until it returns
        yield return uwr.SendWebRequest();

        if (uwr.isNetworkError)
        {
            Debug.Log("Error While Sending: " + uwr.error);
        }
        else
        {
            Debug.Log("Received: " + uwr.downloadHandler.text);
        }
    }
}

[System.Serializable]
public class AppData
{
    public int game_instance = 118;
    public string tracking = "unity";
    public string @event = "start";
    public Meta meta;
}

[System.Serializable]
public class Meta
{
    public string email;
    public bool customTerms;
    public float score;
}
