using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Stove.StoveSDK;
using UnityEngine.UI;


public class AuthUISample : MonoBehaviour
{
    public Toggle verifyIdentificationToggle;
    bool isVerifyIdentification = false;

    // Start is called before the first frame update
    void Start()
    {
        if (verifyIdentificationToggle != null)
        {
            verifyIdentificationToggle.onValueChanged.AddListener(OnVerifyIdentificationToggleChanged);
        }
    }

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

	public void Login()
	{
        Debug.Log("------- [Stove-Sample] AuthUI.Login -------");

        AuthUI.Login((Result result, AccessToken accessToken) =>
        {
            Debug.Log("------- [Stove-Sample] AuthUI.Login : " + result + " -------");

            if (result.IsSuccessful)
            {
                SSTools.ShowMessage("AuthUI.Login Success", SSTools.Position.bottom, SSTools.Time.oneSecond);
            }
            else
            {
                if (result.IsServerError)
                {
                    OperationUI.HandleResult(result, (Result operationResult) =>
                    {
                        if (result.ErrorCode == 44008 || result.ErrorCode == 45006)
                        {
                            PlayerPrefs.DeleteKey("guest");
                            Auth.Logout();
                        }
                    });
                } 
                else if(result.IsCanceled) {
                    MessageDialog.Show("로그인에 실패 하였습니다. 로그인 재 시도 합니다." , () =>
                    {
                        if (Auth.AccessToken != null) {
                            // 로그인 끝난 이후 약관 재동의 or 기기등록 에서 화면을 닫는 상황 or 로그인페이지서 창을 내리는 경우
                            // 토큰이 있는 상황, 무조건 초기화면으로 돌아가서 토큰 검사부터 시작해야함 ( Ex. Touch Screen )
                            Login();
                            SSTools.ShowMessage("AuthUI.Login Fail (Token)", SSTools.Position.bottom, SSTools.Time.oneSecond);
                        } else {
                            // 로그인 완료 전에 화면을 닫는 상황
                            // 토큰이 없는 경우에는 로그인 / 게스트 로그인 버튼 노출 상관 없음
                            SSTools.ShowMessage("AuthUI.Login Fail (Token null) ", SSTools.Position.bottom, SSTools.Time.oneSecond);
                        }
                    });
                } 
                else
                {
                     SSTools.ShowMessage("AuthUI.Login Fail", SSTools.Position.bottom, SSTools.Time.oneSecond);
                }
            }
        });
	}

    public void SetProviders()
    {
        SetProviderDialog.Show(providers =>
        {
            Debug.Log("------- [Stove-Sample] AuthUI.Providers : " + providers + " -------");

            AuthUI.Providers = providers;
        });
    }

    public void Withdraw()
    {
        Debug.Log("------- [Stove-Sample] AuthUI.Withdraw -------");

        AuthUI.Withdraw((Result result) =>
        {
            Debug.Log("------- [Stove-Sample] AuthUI.Withdraw : " + result + " -------");

            if (result.IsSuccessful)
            {
                SSTools.ShowMessage("AuthUI.Withdraw Success", SSTools.Position.bottom, SSTools.Time.oneSecond);
            }
            else
            {
                SSTools.ShowMessage("AuthUI.Withdraw Fail", SSTools.Position.bottom, SSTools.Time.oneSecond);
            }
        });
    }

    public void Link()
    {
        Debug.Log("------- [Stove-Sample] AuthUI.Link -------");

        AuthUI.Link((Result result) =>
        {
            Debug.Log("------- [Stove-Sample] AuthUI.Link : " + result + " -------");

            if (Auth.AccessToken != null)
            {
                if (Auth.AccessToken.User.IsGuest())
                {
                    Debug.Log("------- [Stove-Sample] AuthUI.Link : GUEST -------");
                } else
                {
                    Debug.Log("------- [Stove-Sample] AuthUI.Link : NOT GUEST -------");
                }
            }

            if (result.IsSuccessful)
            {
                SSTools.ShowMessage("AuthUI.Link Success", SSTools.Position.bottom, SSTools.Time.oneSecond);
            }
            else
            {
                SSTools.ShowMessage("AuthUI.Link Fail", SSTools.Position.bottom, SSTools.Time.oneSecond);
            }
        });
    }

    public void ManageAccount()
    {
        Debug.Log("------- [Stove-Sample] AuthUI.ManageAccount -------");

        bool isGuest = false;
        if (Auth.AccessToken != null)
        {
            isGuest = Auth.AccessToken.User.IsGuest();
        }

        AuthUI.ManageAccount((Result result) =>
        {
            Debug.Log("------- [Stove-Sample] AuthUI.ManageAccount : " + result + " -------");

            if (result.IsSuccessful)
            {
                if (result.UserInfo != null && result.UserInfo.TryGetValue("userAction", out string userAction))
                {
                    if (!string.IsNullOrEmpty(userAction) && userAction.Equals("withdraw"))
                    {
                        PlayerPrefs.DeleteKey("guest");
                    }
                }

                SSTools.ShowMessage("AuthUI.ManageAccount Success", SSTools.Position.bottom, SSTools.Time.oneSecond);
            }
            else
            {              
                if (Auth.AccessToken != null)
                {
                    if (!Auth.AccessToken.User.IsGuest() && isGuest)
                    {
                        SSTools.ShowMessage("AuthUI.ManageAccount Conversion to regular membership", SSTools.Position.bottom, SSTools.Time.oneSecond);

                        PlayerPrefs.DeleteKey("guest");

                        bool enable_guid = Constants.Get("enable_guid", false);
                        if (enable_guid) //차후 정회원 전환 API에서 기기등록 여부 결과 주면 적용 임시 GUID 노출
                        {
                            MessageDialog.Show("기기등록을 위해 초기 화면으로 돌아갑니다.(로그인재시도)" , () =>
                            {
                                //기기등록이 필요한 게임의 경우 정회원 전환 이후 초기화 화면으로 전환 ( 기기등록을 하기 위해 )
                                Login();
                            });
                        }
                    } else {
                        SSTools.ShowMessage("AuthUI.ManageAccount Fail", SSTools.Position.bottom, SSTools.Time.oneSecond);

                    }
                } else {
                    SSTools.ShowMessage("AuthUI.ManageAccount Token null", SSTools.Position.bottom, SSTools.Time.oneSecond);
                }
            }
        });
    }

    public void ManageDevices()
    {
        Debug.Log("------- [Stove-Sample] AuthUI.ManageDevices -------");
	    if (Auth.AccessToken != null) {
	        AuthUI.ManageDevices((Result result) =>
        	{
           	    Debug.Log("------- [Stove-Sample] AuthUI.ManageDevices : " + result + " -------");
           	    if (Auth.AccessToken.User.VerifiedDevice) {
                    MessageDialog.Show("등록된 기기 입니다." , () =>
                    {

                    });
           	    } else {
                    MessageDialog.Show("기기등록 필요합니다. 초기화면으로 돌아갑니다." , () =>
                    {

                    });
           	    }
        	});
	    }
    }

    public void VerifyIdentification()
    {
        Debug.Log("------- [Stove-Sample] AuthUI.VerifyIdentification -------");

        if (isVerifyIdentification)
        {
            SSTools.ShowMessage("isVerifyIdentification ON", SSTools.Position.bottom, SSTools.Time.oneSecond);
        } else 
        {
            SSTools.ShowMessage("isVerifyIdentification OFF", SSTools.Position.bottom, SSTools.Time.oneSecond);
        }

        if (Auth.AccessToken != null) {
            AuthUI.VerifyIdentification(isVerifyIdentification, (Result result, string state) =>
            {
                Debug.Log("------- [Stove-Sample] AuthUI.VerifyIdentification : " + result + "state : "+ state +" -------");
                if (result.IsSuccessful)
                {
                    SSTools.ShowMessage("AuthUI.VerifyIdentification Success", SSTools.Position.bottom, SSTools.Time.oneSecond);
                }
                else
                {
                    SSTools.ShowMessage("AuthUI.VerifyIdentification Fail", SSTools.Position.bottom, SSTools.Time.oneSecond);
                }
            });
        }
    }

    public void SwitchAccount()
    {
        Debug.Log("------- [Stove-Sample] AuthUI.SwitchAccount -------");
	    if (Auth.AccessToken != null) {
	        AuthUI.SwitchAccount((Result result) =>
        	{
                Debug.Log("------- [Stove-Sample] AuthUI.SwitchAccount : " + result + " -------");
                if (result.IsSuccessful)
                {
                    SSTools.ShowMessage("AuthUI.SwitchAccount Success", SSTools.Position.bottom, SSTools.Time.oneSecond);
                }
                else
                {
                    SSTools.ShowMessage("AuthUI.SwitchAccount Fail", SSTools.Position.bottom, SSTools.Time.oneSecond);
                }
        	});
	    }
    }

    public void OnVerifyIdentificationToggleChanged(bool isOn)
    {
        isVerifyIdentification = isOn;
    }

    public void Version()
    {
        SSTools.ShowMessage("AuthUI Version : " + AuthUI.GetVersion(), SSTools.Position.bottom, SSTools.Time.oneSecond);
    }
}
