using System.Collections;
using System.Collections.Generic;
using System.Threading.Tasks;
using Google;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class Login : MonoBehaviour
{
    public Button helpBtn;
    public Button googleLoginBtn;
    public Button[] switchBtns;
    public Text statusTxt;

    public GameObject quickLoginPanel, guestLoginPanel;

    public Button BtnGuestLogin;
    public InputField usernameInput, passwordInput;

    bool quickLoginPanelOn =true;
    
    void Awake(){
        helpBtn.onClick.AddListener(OnHelp);
        googleLoginBtn.onClick.AddListener(OnSignIn);
        BtnGuestLogin.onClick.AddListener(OnGuestLogin);
        // guestLoginBtn.onClick.AddListener(SwitchLoginPanel);
        foreach(Button switchBtn in switchBtns){
          switchBtn.onClick.AddListener(SwitchLoginPanel);
        }
        configuration = new GoogleSignInConfiguration {
            WebClientId = webClientId,
            RequestIdToken = true,
            RequestEmail=true,
        };

    }

    async void AutoLogin(){
        Debug.Log("Start auto-login");
        if(PlayerPrefs.HasKey("username")){
          Debug.Log("Has saved credentials, Trying to login with them");
          int loginResult = await DataManager.Login(PlayerPrefs.GetString("username"), PlayerPrefs.GetString("password"));
          if(loginResult == 0){
            LoadingScreen.LoadLevel("MainMenu");
          }else{
            Debug.Log("Failed auto-login");

          }
        }
    }
    void Start(){
        AutoLogin();
    }
    

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

    void OnGuestLogin(){
      if(usernameInput.text.Length < 3){
        MessageBox.ShowMessage("Please enter a username longer than 3 characters");
        return;
      }
      if(usernameInput.text.Contains("#")){
        MessageBox.ShowMessage("Characters like #,$,%,^,& can't be included in username");
        return;
      }

      if(passwordInput.text.Length < 5){
        MessageBox.ShowMessage("Please enter a password with more than 5 characters to stay secure!");
        return;
      }


      DataManager.Login(usernameInput.text, passwordInput.text);
    }


    void OnHelp(){
        MessageBox.ShowMessage("This game saves your progress in cloud, in order to preserve the data. We need you to login with either Google or Guest login.", "Why Login?");
    }

    void SwitchLoginPanel(){
      quickLoginPanelOn = !quickLoginPanelOn;

      LeanTween.scale(quickLoginPanel, quickLoginPanelOn ? Vector3.one : Vector3.zero, 0.5f).setEase(LeanTweenType.easeOutElastic);
      LeanTween.scale(guestLoginPanel, quickLoginPanelOn ? Vector3.zero : Vector3.one, 0.5f).setEase(LeanTweenType.easeOutElastic);
      
    }


     public Text statusText;

    public string webClientId = "<your client id here>";

    private GoogleSignInConfiguration configuration;

    public void OnSignIn() {
      GoogleSignIn.Configuration = configuration;
      GoogleSignIn.Configuration.UseGameSignIn = false;
      GoogleSignIn.Configuration.RequestIdToken = true;
      // AddStatusText("Calling SignIn");

      GoogleSignIn.DefaultInstance.SignIn().ContinueWith(
        OnAuthenticationFinished);
    }

    public void OnSignOut() {
      // AddStatusText("Calling SignOut");
      GoogleSignIn.DefaultInstance.SignOut();
    }

    public void OnDisconnect() {
      // AddStatusText("Calling Disconnect");
      GoogleSignIn.DefaultInstance.Disconnect();
    }

    internal void OnAuthenticationFinished(Task<GoogleSignInUser> task) {
      if (task.IsFaulted) {
        using (IEnumerator<System.Exception> enumerator =
                task.Exception.InnerExceptions.GetEnumerator()) {
          if (enumerator.MoveNext()) {
            GoogleSignIn.SignInException error =
                    (GoogleSignIn.SignInException)enumerator.Current;
            // AddStatusText("Got Error: " + error.Status + " " + error.Message);
            MessageBox.ShowMessage("Got Error: " + error.Status + " " + error.Message);
          } else {
            // AddStatusText("Got Unexpected Exception?!?" + task.Exception);
            MessageBox.ShowMessage("Got Unexpected Exception?!?" + task.Exception);
          }
        }
      } else if(task.IsCanceled) {
        // AddStatusText("Canceled");
        
      } else  {
        // AddStatusText("Welcome: " + task.Result.DisplayName + "!");
        // MessageBox.ShowMessage($"email: {task.Result.Email}\nDisplay:{task.Result.DisplayName}\ntoken:{task.Result.IdToken}");
        StartCoroutine(DoneLogin(task.Result.Email));
      }
    }

    IEnumerator DoneLogin(string username){
      yield return new WaitForSeconds(0.5f);

      DataManager.GoogleLogin(username);
    }

    public void OnSignInSilently() {
      GoogleSignIn.Configuration = configuration;
      GoogleSignIn.Configuration.UseGameSignIn = false;
      GoogleSignIn.Configuration.RequestIdToken = true;
      // AddStatusText("Calling SignIn Silently");

      GoogleSignIn.DefaultInstance.SignInSilently()
            .ContinueWith(OnAuthenticationFinished);
    }


    public void OnGamesSignIn() {
      GoogleSignIn.Configuration = configuration;
      GoogleSignIn.Configuration.UseGameSignIn = true;
      GoogleSignIn.Configuration.RequestIdToken = false;

      // AddStatusText("Calling Games SignIn");

      GoogleSignIn.DefaultInstance.SignIn().ContinueWith(
        OnAuthenticationFinished);
    }

    private List<string> messages = new List<string>();
    
}

