﻿using GameAnvil;
using GameAnvil.Defines;
using GameAnvil.Connection;
using GameAnvil.Connection.Defines;
using UnityEngine;

namespace GameAnvilSampleForTemplate {
    public class Connect : MonoBehaviour {
        [SerializeField]
        Auth authPanel = null;

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

        string getInputIP {
            get { return inputFieldIPAddress.text; }
        }

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

        string getInputPort {
            get { return inputFieldPort.text; }
        }

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

        static public Connect instance = null;

        void Start() {
            ConnectHandler.getInstance().GetConnectionAgent().onErrorCommandListeners
                += (ConnectionAgent connectionAgent, ErrorCode errorCode, Commands commands) => {
                    Debug.LogFormat("errorCommnad - {0}", errorCode);
                };
            ConnectHandler.getInstance().GetConnectionAgent().onErrorCustomCommandListeners
                += (ConnectionAgent connectionAgent, ErrorCode errorCode, string command) => {
                    Debug.LogFormat("onErrorCustomCommand - {0}", errorCode);
                };
            ConnectHandler.getInstance().GetConnectionAgent().onDisconnectListeners
                += (ConnectionAgent connectionAgent, ResultCodeDisconnect result, bool force, Payload payload) => {
                    Debug.LogFormat("onDisconnect - {0}", result);
                    Reset();
                };

            buttonConnect.onClick.AddListener(() => { OnClickConnect(); });
            instance = this;
        }

        public void Reset() {
            this.gameObject.SetActive(true);
            buttonConnect.interactable = true;
            authPanel.Reset();
        }

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

        public void OnClickConnect() {
            buttonConnect.interactable = false;

            Debug.LogFormat("Connect - {0}:{1}", getInputIP, getInputPort);

            // 서버에 접속 시도.
            ConnectHandler.getInstance().GetConnectionAgent().Connect(getInputIP, int.Parse(getInputPort),
                (ConnectionAgent connectionAgent, ResultCodeConnect result) => {
                    Debug.Log(result);
                    if (result == ResultCodeConnect.CONNECT_FAIL) {
                        buttonConnect.interactable = true;
                    } else {
                        // 성공시 다음 단계.
                        OnExit();
                        authPanel.OnEnter();
                    }
                }
            );
        }
    }
}