using System.Collections.Generic;
using Google.Protobuf;
using UnityEngine;

public class PlayerManager : MonoBehaviour
{
    public GameObject playerPrefab;
    public Transform playerScene;

    private Dictionary<long, PlayerMove> _players = new();

    public static PlayerManager Instance { get; private set; }

    private void Awake()
    {
        if (Instance != null)
        {
            Destroy(gameObject);
            return;
        }

        Instance = this;
    }

    private void Start()
    {
        SocketMessageManager.Instance.Subscribe(MessageID.EnterInstance, OnEnterInstance);
        SocketMessageManager.Instance.Subscribe(MessageID.Position, OnPosition);
        SocketManager.Instance.Connect();
    }

    private GameObject AddPlayer(PositionInfo info)
    {
        var player = Instantiate(playerPrefab, playerScene);
        player.GetComponent<PlayerInfo>().usn = info.USN;
        var move = player.GetComponent<PlayerMove>();
        move.SetPosition(info.X, info.Y);
        _players.Add(info.USN, move);
        return player;
    }

    private void OnEnterInstance(ByteString msg)
    {
        var enterInstance = S2C_EnterInstance.Parser.ParseFrom(msg);
        var player = AddPlayer(enterInstance.Info);
        player.AddComponent<PlayerControl>();
    }

    private void OnPosition(ByteString msg)
    {
        var position = S2C_Position.Parser.ParseFrom(msg);
        foreach (var info in position.Info)
        {
            if (!_players.ContainsKey(info.USN))
            {
                AddPlayer(info);
            }
            else
            {
                _players[info.USN].SetPosition(info.X, info.Y);
            }
        }
    }
}