
using Marro.PacManUdon;
using System;
using UdonSharp;
using UnityEngine;

public class NetworkManagerTester : UdonSharpBehaviour
{
    [SerializeField] private NetworkManager[] networkManagers;
    [SerializeField] private float interval = 0.01f;
    [SerializeField] private int ownerIndex = 0;

    private float countdown = 0;
    private bool serializationRequested;

    private void Start()
    {
        foreach (var networkManager in networkManagers)
        {
            networkManager.SetNetworkManagerTester(this);
            if (networkManager.Ready)
            {
                networkManager.Reset();
            }
        }
    }

    private void FixedUpdate()
    {
        countdown -= Time.deltaTime;
        if (countdown > 0)
        {
            return;
        }
        countdown = interval;

        if (!serializationRequested)
        {
            return;
        }

        var source = networkManagers[ownerIndex];

        var data = PerformSerialization(source);

        //Debug.Log($"{nameof(NetworkManagerTester)} Transferring {data.Length} bytes.");

        foreach (var target in networkManagers)
        {
            if (target == source)
            {
                continue;
            }

            PerformDeserialization(target, data);
        }

        serializationRequested = false;
    }

    private byte[] PerformSerialization(NetworkManager networkManager)
    {
        networkManager.OnPreSerialization();
        var data = networkManager.NetworkedData;
        networkManager.OnPostSerializationInternal(true, data.Length);

        return data;
    }

    private byte[] PerformDeserialization(NetworkManager networkManager, byte[] data)
    {
        networkManager.NetworkedData = data;
        networkManager.OnDeserialization();

        return data;
    }

    public bool ShouldBeOwner(NetworkManager manager) => Array.IndexOf(networkManagers, manager) == ownerIndex;

    public void RequestSerializationTest()
    {
        serializationRequested = true;
    }

    public void RequestEvent(NetworkEventType eventType)
    {
        foreach (var target in networkManagers)
        {
            if (!target.IsOwner)
            {
                continue;
            }

            Debug.Log($"{nameof(NetworkManagerTester)} Requested event with type {eventType}.");    

            target.RequestEventReceived(eventType);
        }
    }
}
