using UnityEngine;
using UnityEngine.InputSystem;
using TMPro;
using NeonTea.Quakeball.Networking;
using NeonTea.Quakeball.TeaNet.Peers;
using System;

public class NetDebugScreen : MonoBehaviour {

    public RectTransform BackgroundPanel;
    public TMP_Text ReceivedText;
    public TMP_Text SentText;
    public float UpdateInterval = 5f;

    private InputAction ToggleNetDebug;
    private float LastUpdate;
    private bool IsOpen;

    private void Start() {
        ToggleNetDebug = new InputAction("Toggle Net Debug", binding: "<Keyboard>/F3");
        ToggleNetDebug.Enable();
        ToggleNetDebug.performed += _ => {
            IsOpen = !IsOpen;
            BackgroundPanel.gameObject.SetActive(IsOpen);
        };
    }

    private void Update() {
        bool NetworkingAvailable = Net.Singleton.Instance != null && Net.Singleton.Instance.Peer.Running;
        if (IsOpen && !NetworkingAvailable) {
            ReceivedText.text = "No networking data to show";
            SentText.text = "";
        } else if (IsOpen && NetworkingAvailable) {
            var Peer = Net.Singleton.Instance.Peer;
            if (Time.time - LastUpdate > UpdateInterval) {
                LastUpdate = Time.time;
                TrafficData data = Peer.TrafficData;

                float ToSeconds = 1f / (Peer.TrafficDataInterval / 1000f);
                string received = $"Total incoming traffic: {data.Received * ToSeconds} B/s";
                received += $"\n{data.TotalMessagesReceived * ToSeconds} total messages";
                received += $"\n{data.ReliableReceived * ToSeconds} reliable Packets/s";
                received += $"\n{data.UnreliableReceived * ToSeconds} unreliable Packets/s";
                received += "\nPer packet received traffic:";
                foreach (Type t in data.ReceivedByPacket.Keys) {
                    PerPacketData packetData = data.ReceivedByPacket[t];
                    received += $"\n{t.Name} {packetData.Packets * ToSeconds} P/s - {packetData.Bytes * ToSeconds} B/s";
                }
                ReceivedText.text = received;
                string sent = $"Total outgoing traffic: {data.Sent * ToSeconds} B/s";
                sent += $"\n{data.TotalMessagesSent * ToSeconds} total messages";
                sent += $"\n{data.ReliableSent * ToSeconds} reliable Packets/s";
                sent += $"\n{data.UnreliableSent * ToSeconds} unreliable Packets/s";
                sent += "\nPer packet sent traffic:";
                foreach (Type t in data.SentByPacket.Keys) {
                    PerPacketData packetData = data.SentByPacket[t];
                    sent += $"\n{t.Name} {packetData.Packets * ToSeconds} P/s - {data.SentByPacket[t].Bytes * ToSeconds} B/s";
                }
                SentText.text = sent;
            }
        }
    }
}
