using AllocsFixes.PersistentData;
using System;
using System.Collections.Generic;
using UnityEngine;

namespace AllocsFixes
{
	public class AllocsLogFunctions
	{
		public static void RequestToSpawnPlayer (GameManager manager, int _clientId, string _name, int _chunkViewDim, PlayerProfile _playerProfile)
		{
			try {
				ClientInfo ci = CommonMappingFunctions.GetClientInfoFromClientID (_clientId);
				int entityId = CommonMappingFunctions.GetEntityID (ci);
				EntityPlayer ep = CommonMappingFunctions.GetEntityPlayer (ci);
				string steamId = CommonMappingFunctions.GetSteamID (ci);

				string ip = ci.networkPlayer.ipAddress;
				string name = string.Empty;

				if (ep != null)
					name = ep.EntityName;

				Log.Out ("Player connected, clientid=" + _clientId +
					", entityid=" + entityId +
					", name=" + name +
					", steamid=" + steamId +
					", ip=" + ip
				);

				PersistentContainer.Instance.Players [steamId].SetOnline (ci);
				PersistentData.PersistentContainer.Instance.Save ();

				Mods.CallRequestToSpawnPlayer (_clientId, _name, _chunkViewDim, _playerProfile);
			} catch (Exception e) {
				Log.Out ("Error in AllocsLogFunctions.RequestToSpawnPlayer: " + e);
			}
		}

		public static void PlayerDisconnected (ConnectionManager manager, ClientInfo _cInfo, bool _bShutdown)
		{
			try {
				Player p = PersistentContainer.Instance.Players [_cInfo.playerId];
				if (p != null) {
					p.SetOffline ();
				} else {
					Log.Out ("Disconnected player not found in client list...");
				}
				PersistentData.PersistentContainer.Instance.Save ();

				Mods.CallPlayerDisconnected (_cInfo, _bShutdown);
			} catch (Exception e) {
				Log.Out ("Error in AllocsLogFunctions.PlayerDisconnected: " + e);
			}
		}
	}
}
