using System;
using System.Collections.Generic;
using System.Linq;
using Fusion;
using Fusion.Sockets;
using UnityEngine;
using UnityEngine.SceneManagement;

namespace Squelette {
	public class NetworkRunnerHelper : MonoBehaviour, INetworkRunnerCallbacks {
		NetworkRunner runner;

		void Start() => JoinGame();
		
		async void JoinGame() {
			if (runner is not null)
				return;
			
			runner = GetComponent<NetworkRunner>();
			runner.ProvideInput = true;

			print("Starting game!");
			await runner.StartGame(new StartGameArgs {
				GameMode = GameMode.AutoHostOrClient,
				SessionName = "SingleSession",
				Scene = SceneManager.GetActiveScene().buildIndex,
				SceneObjectProvider = gameObject.AddComponent<NetworkSceneManagerDefault>()
			});
		}

		public void OnPlayerJoined(NetworkRunner runner, PlayerRef player) {
			print($"Player {player.PlayerId} just joined!");
		}

		public void OnPlayerLeft(NetworkRunner runner, PlayerRef player) {
			print($"Player {player.PlayerId} just left!");
		}
		public void OnInput(NetworkRunner runner, NetworkInput input) {}
		public void OnInputMissing(NetworkRunner runner, PlayerRef player, NetworkInput input) {}
		public void OnShutdown(NetworkRunner runner, ShutdownReason shutdownReason) {}

		public void OnConnectedToServer(NetworkRunner runner) {
			print($"Connected to server! {runner.ActivePlayers.Count()} players connected!");
		}

		public void OnDisconnectedFromServer(NetworkRunner runner) {
			print("Disconnected from server!");
		}
		public void OnConnectRequest(NetworkRunner runner, NetworkRunnerCallbackArgs.ConnectRequest request, byte[] token) {}
		public void OnConnectFailed(NetworkRunner runner, NetAddress remoteAddress, NetConnectFailedReason reason) {}
		public void OnUserSimulationMessage(NetworkRunner runner, SimulationMessagePtr message) {}
		public void OnSessionListUpdated(NetworkRunner runner, List<SessionInfo> sessionList) {}
		public void OnCustomAuthenticationResponse(NetworkRunner runner, Dictionary<string, object> data) {}
		public void OnHostMigration(NetworkRunner runner, HostMigrationToken hostMigrationToken) {}
		public void OnReliableDataReceived(NetworkRunner runner, PlayerRef player, ArraySegment<byte> data) {}
		public void OnSceneLoadDone(NetworkRunner runner) {}
		public void OnSceneLoadStart(NetworkRunner runner) {}
	}
}