using System.Collections;
using Unity.Netcode;
using UnityEngine;

public class SinglePooledDynamicSpawner : NetworkBehaviour, INetworkPrefabInstanceHandler
{
    public GameObject PrefabToSpawn;
    public bool SpawnPrefabAutomatically;

    private GameObject m_PrefabInstance;
    private NetworkObject m_SpawnedNetworkObject;

    private void Start()
    {
        //客户端和服务端，都先实例化物体
        m_PrefabInstance = Instantiate(PrefabToSpawn);
        m_SpawnedNetworkObject = m_PrefabInstance.GetComponent<NetworkObject>();
        m_PrefabInstance.SetActive(false);
    }

    //延迟2秒后，NetworkObject.Despawn
    private IEnumerator DespawnTimer()
    {
        yield return new WaitForSeconds(2);
        m_SpawnedNetworkObject.Despawn();
        StartCoroutine(SpawnTimer());
        yield break;
    }

    //延迟2秒手
    private IEnumerator SpawnTimer()
    {
        yield return new WaitForSeconds(2);
        SpawnInstance();
        yield break;
    }

    //实现INetworkPrefabInstanceHandler.Instantiate方法，客户端调用
    public NetworkObject Instantiate(ulong ownerClientId, Vector3 position, Quaternion rotation)
    {
        m_PrefabInstance.SetActive(true);
        m_PrefabInstance.transform.position = transform.position;
        m_PrefabInstance.transform.rotation = transform.rotation;

        return m_SpawnedNetworkObject;
    }

    //客户端和服务端
    //实现INetworkPrefabInstanceHandler.Destroy
    public void Destroy(NetworkObject networkObject)
    {
        m_PrefabInstance.SetActive(false);
    }

    public void SpawnInstance()
    {
        if(!IsServer)
        {
            return;
        }

        if(m_PrefabInstance != null && m_SpawnedNetworkObject != null && !m_SpawnedNetworkObject.IsSpawned)
        {
            m_PrefabInstance.SetActive(true);
            m_SpawnedNetworkObject.Spawn();

            StartCoroutine(DespawnTimer());
        }
    }

    public override void OnNetworkSpawn()
    {
        //注册自己
        NetworkManager.PrefabHandler.AddHandler(PrefabToSpawn, this);

        if(!IsServer || !SpawnPrefabAutomatically)
        {
            return;
        }

        if(SpawnPrefabAutomatically)
        {
            SpawnInstance();
        }
    }

    public override void OnNetworkDespawn()
    {
        if(m_SpawnedNetworkObject != null && m_SpawnedNetworkObject.IsSpawned)
        {
            m_SpawnedNetworkObject.Despawn();
        }

        base.OnNetworkDespawn();
    }

    public override void OnDestroy()
    {
        if(m_PrefabInstance != null)
        {
            NetworkManager.Singleton.PrefabHandler.RemoveHandler(PrefabToSpawn);

            Destroy(m_PrefabInstance);
        }

        base.OnDestroy();
    }
}