using UnityEngine;
using NeonTea.Quakeball.Networking.Instances;
using NeonTea.Quakeball.TeaNet.Peers;
using NeonTea.Quakeball.TeaNet.Packets;
using System.Collections.Generic;

namespace NeonTea.Quakeball.Networking {

    public class Net {
        public static Net Singleton = new Net();

        public NetInstance Instance;

        public void StartClient(string address, int port, PeerMessageListener listener) {
            Instance = new Client();
            Instance.Start(address, port, listener);
        }

        public void StartServer(string address, int port, PeerMessageListener listener) {
            Instance = new Server();
            Instance.Start(address, port, listener);
        }

        public static void Quit() {
            if (Singleton.Instance != null) {
                Singleton.Instance.Stop();
            }
        }

        [RuntimeInitializeOnLoadMethod]
        static void RunOnStart() {
            Application.quitting += Quit;
        }
    }


    public static class ByteBufferExtensions {
        /// <summary>Extension: Reads Vector3</summary>
        public static Vector3 ReadVector3(this ByteBuffer buffer) {
            float x = buffer.ReadFloat();
            float y = buffer.ReadFloat();
            float z = buffer.ReadFloat();
            return new Vector3(x, y, z);
        }

        /// <summary>Extension: Writes Vector3</summary>
        public static void Write(this ByteBuffer buffer, Vector3 vector) {
            buffer.Write(vector.x);
            buffer.Write(vector.y);
            buffer.Write(vector.z);
        }
    }
}
