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

namespace NeonTea.Quakeball.Networking {

    public class GameProtocol : Protocol {
        public override byte Identifier => 0x7A;

        public override string Version => "0.0.1";

        private NetInstance Instance;

        public GameProtocol(NetInstance instance) {
            Instance = instance;
            RegisterPacket(typeof(HelloPckt));
            RegisterPacket(typeof(PingPckt));
            RegisterPacket(typeof(SpawnPckt));
            RegisterPacket(typeof(SelfIdentPckt));
            RegisterPacket(typeof(PlayerUpdatePckt));
            RegisterPacket(typeof(PlayerActionPckt));
            RegisterPacket(typeof(PlayerSyncPacket));
            RegisterPacket(typeof(MultiplePlayerUpdatesPckt));
            RegisterPacket(typeof(MultipleSyncsPckt));
        }

        public override void ConnectionStatusChanged(ConnectionStatus oldStatus, ConnectionStatus newStatus, Connection conn) {
            if (conn.IsReady() && !Instance.Connections.Contains(conn.uid)) {
                Instance.Connected(conn);
            } else if (conn.IsDisconnected()) {
                Instance.Disconnected(conn);
            }
        }

        public override void Receive(Connection conn, Packet packet) {
            Instance.Handle(conn, packet);
        }

        public override void Timeout(Connection conn) {
            Instance.Disconnected(conn);
        }
    }
}
