﻿using System.Collections.Generic;
using GameAnvil;
using GameAnvil.Defines;
using GameAnvil.Connection;
using UnityEngine;

namespace GameAnvilSampleForTemplate
{
    public class Auth : MonoBehaviour
    {
        [SerializeField]
        ServiceLogin serviceLogin = null;

        [SerializeField]
        UnityEngine.UI.InputField userID_InputField = null;

        string getInputID {
            get { return userID_InputField.text; }
        }

        [SerializeField]
        UnityEngine.UI.InputField userPass_InputField = null;

        string getInputPassword {
            get { return userPass_InputField.text; }
        }

        [SerializeField]
        UnityEngine.UI.Button login_Button = null;

        void Start()
        {
            login_Button.onClick.AddListener(() => { OnClick_Auth(); });
        }

        public void Reset()
        {
            this.gameObject.SetActive(false);
            Restore();
            serviceLogin.Reset();
        }

        public void OnEnter()
        {
            Restore();
            this.gameObject.SetActive(true);
        }

        void Restore()
        {
            login_Button.interactable = true;
        }

        void OnExit()
        {
            this.gameObject.SetActive(false);
        }

        void DisableInput()
        {
            login_Button.interactable = false;
        }

        void OnClick_Auth()
        {
            Debug.Log("OnClick_Auth");
            DisableInput();

            // 서버에 인증을 요청.
            ConnectHandler.getInstance().GetConnectionAgent().Authenticate("", getInputID, getInputPassword,
                (ConnectionAgent connectionAgent, ResultCodeAuth result, List<ConnectionAgent.LoginedUserInfo> loginedUserInfoList, string message, Payload payload) => {
                    Debug.Log(result);
                    // 성공인 경우 다음 단계로 진행.
                    if (result == ResultCodeAuth.AUTH_SUCCESS)
                    {
                        OnExit();
                        serviceLogin.OnEnter();
                    } else
                    {
                        Restore();
                    }
                }
            );
        }
    }
}