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

using UnityEngine.UI;

using UnityEngine.Networking;
using System.Linq;

public class MasterCreateGame : MonoBehaviour
{
    private string gameNumber;

    public Text gameDisplayNumber;
    public GameObject selectionPanel;
    public GameObject errorPanel;
    public GameObject connectingPanel;
    public GameObject playerNumberInput;
    public GameObject locationInput;

    // Start is called before the first frame update
    void Start()
    {
        string serverUrl_nextGame = "https://smarthubs.media.tuwien.ac.at/api/get_next_game_id";
        StartCoroutine(getNextId(serverUrl_nextGame));
        
        // GET THE NEW GAME ID FROM SERVER 
        // SHOVE IT INTO THE GAME NUMBER FIELD

    }

    // Update is called once per frame
    void Update()
    {
        
    }

    public void CreateGameHelper()
    {
        // SEND THE CREATE GAME TO SERVER
        string serverUrl_createGame = "https://smarthubs.media.tuwien.ac.at/api/create_game";

        connectingPanel.SetActive(true);

        StartCoroutine(CreateGame(serverUrl_createGame));

        connectingPanel.SetActive(false);

    }


    public IEnumerator getNextId(string serverUrl_nextGame)
    {
        UnityWebRequest www = UnityWebRequest.Get(serverUrl_nextGame);

        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 next_game_id = www.downloadHandler.text;

            Debug.Log(next_game_id);
            this.gameNumber = next_game_id;
            // DSISPLAY GAME NUMBER
            this.gameDisplayNumber.text = next_game_id;

        }

    }

    public IEnumerator CreateGame(string ServerUrl)
    {
        string players = "4";
        string location = locationInput.GetComponent<InputField>().text;

        if(location == null)
            location = "";
        if(players == null)
            players = "";

        WWWForm form = new WWWForm();
        
        form.AddField("players", players);
        form.AddField("location", location);

        using (UnityWebRequest www = UnityWebRequest.Post(ServerUrl, form))
        {
            yield return www.SendWebRequest();

            if (www.result != UnityWebRequest.Result.Success)
            {
                Debug.Log(www.error);
                // PROMPT ERROR
                errorPanel.SetActive(true);
            }
            else
            {
                Debug.Log("Form upload complete!");
                Debug.Log(www.downloadHandler.text);
                // CLOSE THE PANEL
                this.selectionPanel.SetActive(false);
            }
        }
    }

    public string GetGameNumber()
    {
        return this.gameNumber;
    }
}