﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using Combu;
using Combu.Addons;
using Facebook.Unity;

public class CombuFacebookLogin : MonoBehaviour
{
    public GameObject rootContainer;
    public InputField inputUsername;
    public InputField inputPassword;
    public Text textError;

    string localFacebookID;

    void Start()
    {
        FB.Init();
    }

    void LogError(string error)
    {
        if (textError != null)
            textError.text = error;
    }

    void OnLoginResult(bool success, string error)
    {
        // Do your stuff here upon login result from Combu...
        LogError(success ? "Logged in as " + CombuManager.localUser.userName : error);
        if (success)
            gameObject.SetActive(false);
    }

    /// <summary>
    /// Handler for the button to connect with Facebook.
    /// </summary>
    public void ConnectWithFacebook ()
    {
        if (FB.IsInitialized && CombuManager.isInitialized)
        {
            LogError("");
            var permissions = new List<string>() { "public_profile", "email" };
            FB.LogInWithReadPermissions(permissions, (ILoginResult result) =>
            {
                Debug.Log("Logged in: " +FB.IsLoggedIn + " -- Facebook ID: " + result.AccessToken.UserId);
                if (FB.IsLoggedIn && !string.IsNullOrEmpty(result.AccessToken.UserId))
                {
                    // Cache the user's Facebook ID
                    localFacebookID = result.AccessToken.UserId;
                    // Search for users with this Facebook ID
                    User.LoadPlatform(new string[] { "Facebook" }, new string[] { localFacebookID }, (User[] users) =>
                    {
                        if (users.Length > 0)
                        {
                            Debug.Log("Account found for " + localFacebookID);
                            // Facebook ID is already associated to an account
                            AuthenticateWithFacebook();
                        }
                        else
                        {
                            // Facebook ID is NOT associated to any account
                            Debug.Log("No account found for " + localFacebookID + ", getting Facebook profile");
                            FB.API("/me", HttpMethod.GET, (IGraphResult resultMe) =>
                            {
                                if (string.IsNullOrEmpty(resultMe.Error))
                                {
                                    string email = "";
                                    if (resultMe.ResultDictionary.ContainsKey("email") && resultMe.ResultDictionary["email"] != null)
                                        email = resultMe.ResultDictionary["email"].ToString();
                                    if (string.IsNullOrEmpty(email))
                                    {
                                        // Could not get the email from Facebook login, try to authenticate on Combu by Facebook ID
                                        Debug.Log("No email found on Facebook profile for " + localFacebookID);
                                        AuthenticateWithFacebook();
                                    }
                                    else
                                    {
                                        // An email address was found in the Facebook profile, search for an existing account
                                        User.Exists(string.Empty, email, (bool userExists, string userError) =>
                                        {
                                            Debug.Log("User exists: " + userExists + " > " + userError);
                                            if (userExists)
                                            {
                                            /*
                                             * The email from Facebook is already associated to an account, remember to enable
                                             * the container for your username/email and password (and "Link/Login" button)
                                             * by adding handler to your "Connect with Facebook" button's click,
                                             * and the "Link/Login" button must have a click handler calling the method ConnectWithCombu()
                                             */
                                                if (inputUsername != null)
                                                    inputUsername.text = email;
                                                if (rootContainer != null)
                                                    rootContainer.SetActive(true);
                                                gameObject.SetActive(false);
                                            }
                                            else
                                            {
                                            /*
                                             * No accounts are associated to this email,
                                             * create a new account for this Facebook ID
                                             */
                                                AuthenticateWithFacebook();
                                            }
                                        });
                                    }
                                }
                                else
                                {
                                    LogError(resultMe.Error);
                                }
                            });
                        }
                    });
                }
                else
                {
                    LogError("Login on Facebook " + (result.Cancelled ? "cancelled" : "failed"));
                }
            });
        }
	}

    /// <summary>
    /// Handler for the button to link an existing account to Facebook.
    /// </summary>
    public void ConnectWithCombu()
    {
        string username = (inputUsername != null ? inputUsername.text.Trim() : "");
        string password = (inputPassword != null ? inputPassword.text.Trim() : "");

        if (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))
        {
            LogError("Enter your existing username/email and password");
        }
        else
        {
            CombuManager.platform.Authenticate(username, password, (bool success, string error) =>
            {
                if (success)
                {
                    CombuManager.localUser.LinkPlatform("Facebook", localFacebookID, (bool linkSuccess, string linkError) =>
                    {
                        if (linkSuccess)
                            OnLoginResult(true, string.Empty);
                        else
                            LogError("Link to Facebook failed: " + linkError);
                    });
                    transform.parent.gameObject.SetActive(false);
                }
                else
                {
                    LogError("Login on Combu failed: " + error);
                }
            });
        }
    }

    /// <summary>
    /// Callback to invoke to authenticate on Combu with Facebook ID.
    /// </summary>
    void AuthenticateWithFacebook()
    {
        CombuManager.localUser.AuthenticatePlatform("Facebook", localFacebookID, OnLoginResult);
    }
}
