using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class Login : MonoBehaviour
{
    public InputField loginInput;
    public Button loginBtn;


    void Awake(){
        if(DataManager.LoggedIn){
            DataManager.LoadFromSave();
            SceneManager.LoadScene(1);
        }
        loginBtn.onClick.AddListener(OnLogin);
        loginInput.onValueChanged.AddListener(OnInputChanged);

        loginBtn.interactable=false;
    }
    public void OnLogin(){
        StartCoroutine(login(loginInput.text));
    }

    void OnInputChanged(string newVal){
        loginBtn.interactable = newVal.Length > 2;
    }

    IEnumerator login(string username){
        WWWForm form = new WWWForm();
        form.AddField("username", username);
        form.AddField("key","#2CuV1Bit^S!sW1ZcgRv8BhrO");

        WWW req = new WWW(DataManager.API_Endpoint +"register_instant.php", form);
        yield return req;

        if(DataManager.OnLoginDone(username, req.text)){
            SceneManager.LoadScene(1);
        }        
    }
}
