using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using UnityEngine;
using Object = UnityEngine.Object;

namespace FastArena
{
    public static class Client
    {
        private static TcpClient _tcp;
        private static UdpClient _udp;
        
        public static void SendUserAction()
        {
            throw new System.NotImplementedException();
        }

        public static void Connect(IPAddress ip, short portFirst)
        {
            _tcp = new TcpClient();
            _udp = new UdpClient();
            _tcp.BeginConnect(ip, portFirst, TCPConnectCallback, null);
            _udp.BeginSend(StructBinaryConverter.GetBytes(new ConnectionRequestUDP()))
        }

        private static void TCPConnectCallback(IAsyncResult ar)
        {
            _tcp.EndConnect(ar);
        }

        private static Dictionary<int, SyncTransform> _syncTransforms = new();

        private static void CreateGameObject(int id, ref CreateObjectPacket packet)
        {
            var prefab = Resources.Load(packet.prefabPath, typeof(GameObject));
            var go = (GameObject)Object.Instantiate(prefab);
            var idComponent = go.AddComponent<GameObjectId>();
            idComponent._SetId(packet.gameObjectId);
            if (go.TryGetComponent(out SyncTransform syncTransform))
            {
                _syncTransforms.Add(packet.gameObjectId, syncTransform);
            }
        }
        
        private static void UpdateObjectTransform(int id, ref TransformUpdatePacket packet)
        {
            if(!_syncTransforms.TryGetValue(id, out var component))
                return;
            component.UpdateTransform(ref packet);
        }
    }
}