using System;
using Unity.Netcode;
using UnityEngine;

//StartHost开启服务端
class StartingHostState : OnlineState
{
    ConnectionMethodIP m_ConnectionMethod;

    public StartingHostState Configure()
    {
        m_ConnectionMethod = m_ConnectionManager.ConnectionMethod;
        return this;
    }

    public override void Enter()
    {
        StartHost();
    }

    public override void Exit()
    {
    }

    //StartHost失败
    public override void OnClientDisconnect(ulong clientId)
    {
        if(clientId == m_ConnectionManager.NetworkManager.LocalClientId)
        {
            StartHostFailed();
        }
    }

    //StartHost失败。跳转到OfflineState
    void StartHostFailed()
    {
        MessageCenter.SendMessage(EventDefine.ConnectStatusEvent, ConnectStatus.StartHostFailed);
        m_ConnectionManager.ChangeState(m_ConnectionManager.m_Offline);
    }

    //StartHost成功，跳转到HostingState
    public override void OnServerStarted()
    {
        MessageCenter.SendMessage(EventDefine.ConnectStatusEvent, ConnectStatus.Success);
        m_ConnectionManager.ChangeState(m_ConnectionManager.m_Hosting);
    }

    //此处的检查主要是针对Host的客户端自己连接。当启动Host时，就会创建本地客户端，并连接触发此处调用
    public override void ApprovalCheck(NetworkManager.ConnectionApprovalRequest request, NetworkManager.ConnectionApprovalResponse response)
    {
        var connectionData = request.Payload;
        var clientId = request.ClientNetworkId;

        if(clientId == m_ConnectionManager.NetworkManager.LocalClientId)
        {
            var payload = System.Text.Encoding.UTF8.GetString(connectionData);
            var connectionPayload = JsonUtility.FromJson<ConnectionPayload>(payload);

            //保存Host客户端登录数据
            PlayerManager.Instance.SetupConnectingPlayerSessionData(clientId, connectionPayload.playerId,
                new PlayerData(clientId, connectionPayload, true));

            response.Approved = true;
            //Host客户端，需要生成预设物体
            response.CreatePlayerObject = true;
        }
    }

    //启动服务端
    async void StartHost()
    {
        try
        {
            //设置IP、端口
            await m_ConnectionMethod.SetupHostConnectionAsync();

            //开启Host
            if(!m_ConnectionManager.NetworkManager.StartHost())
            {
                //如果启动失败
                OnClientDisconnect(m_ConnectionManager.NetworkManager.LocalClientId);
            }

        }
        catch(Exception)
        {
            StartHostFailed();

            throw;
        }
    }
}
