using FishNet;
using FishNet.Connection;
using FishNet.Managing.Scened;
using FishNet.Object;
using UnityEngine;
using IStalk.Network;

namespace IStalk.Core
{
    public class PlayerSpawner : MonoBehaviour
    {
        [SerializeField] private NetworkObject _runnerPrefab;
        [SerializeField] private NetworkObject _eyePrefab;

        private MapGenerator _mapGenerator;
        private int _spawnedRunners;

        private void Start()
        {
            _mapGenerator = FindAnyObjectByType<MapGenerator>();

            if (InstanceFinder.IsServerStarted)
            {
                InstanceFinder.SceneManager.OnClientLoadedStartScenes += OnClientReady;
                SpawnLocalPlayer();
            }
        }

        private void OnDestroy()
        {
            if (InstanceFinder.SceneManager != null)
                InstanceFinder.SceneManager.OnClientLoadedStartScenes -= OnClientReady;
        }

        private void OnClientReady(NetworkConnection conn, bool asServer)
        {
            if (!asServer) return;
            SpawnPlayerForConnection(conn, false);
        }

        private void SpawnLocalPlayer()
        {
            var conn = InstanceFinder.ClientManager.Connection;
            SpawnPlayerForConnection(conn, true);
        }

        private void SpawnPlayerForConnection(NetworkConnection conn, bool isEye)
        {
            NetworkObject prefab = isEye ? _eyePrefab : _runnerPrefab;
            Vector3 spawnPos = GetSpawnPosition(isEye);

            NetworkObject spawned = Instantiate(prefab, spawnPos, Quaternion.identity);
            InstanceFinder.ServerManager.Spawn(spawned, conn);
        }

        private Vector3 GetSpawnPosition(bool isEye)
        {
            if (isEye)
                return _mapGenerator != null ? _mapGenerator.GetMapCenter() : Vector3.zero;

            return _mapGenerator != null ? _mapGenerator.GetRunnerSpawnPoint() : Vector3.zero;
        }
    }
}
