using System;
using System.Threading.Tasks;
using Unity.Netcode.Transports.UTP;
using UnityEngine;

//客户端数据（发给服务端）
[Serializable]
public class ConnectionPayload
{
    public string ip;
    public string playerId;
    public string playerName;
    //客户端是否Debug版本
    public bool isDebug;
    //是否走视频流
    public bool isVideo;
    //是否需要生成锚点
    public bool needAnchor;
}

//在OfflineState中创建
public class ConnectionMethodIP
{
    protected ConnectionManager m_ConnectionManager;

    //提供缓存信息（客户端本地缓存，音量等参数）
    readonly ProfileManager m_ProfileManager;

    //玩家数据
    public ConnectionPayload connectionData;

    //IP端口
    private string m_Ipaddress;
    private ushort m_Port;

    public ConnectionMethodIP(ConnectionManager connectionManager,ProfileManager profileManager)
    {
        m_ConnectionManager = connectionManager;
        m_ProfileManager = profileManager;

        connectionData = new ConnectionPayload()
        {
            playerId = GetPlayerId(true),
            playerName = "Null",
            isDebug = Debug.isDebugBuild,
            isVideo = false,
            needAnchor = false,
        };
    }

    public void SetConnectionData(string clientIP, string clientName, bool isVideo, bool needAnchor)
    {
        connectionData.ip = clientIP;
        connectionData.playerName = clientName;
        connectionData.isVideo = isVideo;
        connectionData.needAnchor = needAnchor;
    }

    public void SetIPData(string ip, ushort port)
    {
        m_Ipaddress = ip;
        m_Port = port;
    }

    //设置客户端登录账号信息ConnectionPayload
    protected void SetConnectionPayload()
    {
        //转成Json
        var payload = JsonUtility.ToJson(connectionData);

        //转成字节流（UTF8）
        var payloadBytes = System.Text.Encoding.UTF8.GetBytes(payload);

        //交给NetworkManager.NetworkConfig.ConnectionData
        m_ConnectionManager.NetworkManager.NetworkConfig.ConnectionData = payloadBytes;
    }

    //每个客户端必须独一无二，由客户端本地生成
    protected string GetPlayerId(bool isNew)
    {
        //默认以设备名称作为用户名
        return ClientPrefs.GetGuid(isNew);
    }


    //设置客户端账号。设置服务端的IP、Port
    public async Task SetupClientConnectionAsync()
    {
        //客户端账号
        SetConnectionPayload();

        //服务端IP、端口
        UnityTransport utp = (UnityTransport)m_ConnectionManager.NetworkManager.NetworkConfig.NetworkTransport;
        utp.SetConnectionData(m_Ipaddress, m_Port);
    }

    //设置Host的IP、Port
    public async Task SetupHostConnectionAsync()
    {
        //Host模式也是客户端，也需要设置客户端账号
        SetConnectionPayload();

        //设置服务端监听IP、端口
        UnityTransport utp = (UnityTransport)m_ConnectionManager.NetworkManager.NetworkConfig.NetworkTransport;
        utp.SetConnectionData(m_Ipaddress, m_Port);
    }
}
