using System;
using System.Threading.Tasks;
using Unity.Multiplayer.Samples.Utilities;
using UnityEngine;

//客户端正在连接
public class ClientConnectingState : OnlineState
{
    ConnectionMethodIP m_ConnectionMethod;

    //设置客户端账号、服务端IP、端口
    public ClientConnectingState Configure()
    {
        m_ConnectionMethod = m_ConnectionManager.ConnectionMethod;
        return this;
    }

    public override void Enter()
    {
#pragma warning disable 4014
        ConnectClientAsync();
#pragma warning restore 4014
    }

    public override void Exit()
    {
    }

    //客户端连接成功。切换到ClientConnectedState状态
    public override void OnClientConnected(ulong clientId)
    {
        MessageCenter.SendMessage(EventDefine.ConnectStatusEvent, ConnectStatus.Success);

        m_ConnectionManager.ChangeState(m_ConnectionManager.m_ClientConnected);
    }

    //StartingClient失败
    public override void OnClientDisconnect(ulong clientId)
    {
        StartingClientFailedAsync();
    }

    //StartingClient失败。切换到OfflineState状态
    protected void StartingClientFailedAsync()
    {
        MessageCenter.SendMessage(EventDefine.ConnectStatusEvent, ConnectStatus.StartClientFailed);

        m_ConnectionManager.ChangeState(m_ConnectionManager.m_Offline);
    }

    //与服务器断开连接。切换到DisconnectingWithReasonState状态
    public override void OnDisconnectReasonReceived(ConnectStatus disconnectReason)
    {
        MessageCenter.SendMessage(EventDefine.ConnectStatusEvent, disconnectReason);
        //MessageCenter.SendMessage(EventDefine.ClientDisConnectionEvent, disconnectReason);

        m_ConnectionManager.ChangeState(m_ConnectionManager.m_DisconnectingWithReason);
    }

    //开始连接
    internal async Task ConnectClientAsync()
    {
        try
        {
            //设置IP、端口
            await m_ConnectionMethod.SetupClientConnectionAsync();

            //StartClient开始连接
            if(!m_ConnectionManager.NetworkManager.StartClient())
            {
                throw new Exception("NetworkManager StartClient failed");
            }

            //注册自定义消息
            m_ConnectionManager.RegisterCustomMessages();
        }
        catch(Exception e)
        {
            Debug.LogError("Error connecting client, see following exception");
            Debug.LogException(e);

            StartingClientFailedAsync();

            throw;
        }
    }
}
