using System.Collections;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.SceneManagement;
using static CommunicationEvents;

public class WaitingForLocalMMT : MonoBehaviour
{
    private void OnEnable()
    {
        StartCoroutine(ServerRoutine());
    }

    private void OnDisable()
    {
        StopCoroutine(ServerRoutine());
    }

    void PrepareGame()
    {
        //This condition should always be true if PrepareGame gets called, but it never hurts to make sure.
        if (CommunicationEvents.ServerRunning)
        {
            CommunicationEvents.ServerAdress = "http://" + CommunicationEvents.ServerAddressLocal; //ServerAddress needs the "http://"
            //UnityEngine.Debug.Log("StartMainMenu");
            // TODO: Display "Loading in progress" to the player
            SceneManager.LoadScene("MainMenu");
        }
    }

    IEnumerator ServerRoutine()
    {
        yield return ServerSlots[ServerSlot.localServer].UpdateServerStatus(skipIfAlreadyChecked: false);

        // The address of the localServer currently cannot change, so it is never empty/illegal
        // If this can happen in the future, this condition may not suffice
        while (ServerSlots[ServerSlot.localServer].currentStatus != ServerStatus.online)
        {
            Debug.Log("Local MMT Server not ready yet\n Will try again in 2 sec.");
            yield return new WaitForSecondsRealtime(2f);
            yield return ServerSlots[ServerSlot.localServer].UpdateServerStatus(skipIfAlreadyChecked: false);
        }

        Debug.Log("Preparing game now");
        CommunicationEvents.ServerRunning = true;
        // Give Unity time to flush the debug log
        yield return new WaitForSecondsRealtime(0.1f);
        PrepareGame();
    }

    public UnityWebRequest pingL()
    {
        //UnityWebRequest request = UnityWebRequest.Get("http://" + NetwAddress + "/scroll/list");
        //using UnityWebRequest request = UnityWebRequest.Get(CommunicationEvents.ServerAddressLocal + "/scroll/list");
        UnityWebRequest request = UnityWebRequest.Get("http://" + CommunicationEvents.ServerAddressLocal + "/fact/list");
        return request;
    }
}