//
// HandshakeResponder.cs
//
// Copyright (c) František Boháček. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Extensions.Logging;
using NosSmooth.Comms.Core;
using NosSmooth.Comms.Data.Messages;
using NosSmooth.Comms.Data.Responders;
using NosSmooth.LocalBinding;
using Remora.Results;
namespace NosSmooth.Comms.Inject.MessageResponders;
///
/// A responder to .
///
public class HandshakeResponder : IMessageResponder
{
private readonly ClientState _state;
private readonly NosBrowserManager _browserManager;
private readonly ConnectionHandler _connectionHandler;
private readonly CallbackConfigRepository _config;
private readonly ILogger _logger;
///
/// Initializes a new instance of the class.
///
/// The state of the application.
/// The browser manager.
/// The connection handler.
/// The config.
/// The logger.
public HandshakeResponder
(
ClientState state,
NosBrowserManager browserManager,
ConnectionHandler connectionHandler,
CallbackConfigRepository config,
ILogger logger
)
{
_state = state;
_browserManager = browserManager;
_connectionHandler = connectionHandler;
_config = config;
_logger = logger;
}
///
public async Task Respond(HandshakeRequest message, CancellationToken ct = default)
{
var config = new CallbackConfig(message.SendRawPackets, message.SendDeserializedPackets);
_config.SetConfig(_connectionHandler, config);
string? playerName = null;
long? playerId = null;
if (_browserManager.IsInGame)
{
playerName = _browserManager.PlayerManager.Player.Name;
playerId = _browserManager.PlayerManager.PlayerId;
}
var result = await _connectionHandler.SendMessageAsync
(
new HandshakeResponse(_state.IsRunning, _state.InitResult, playerId, playerName),
ct
);
_logger.LogInformation
(
"Handshaked with {Identification}! (connection {ConnectionID})",
message.Identification,
_connectionHandler.Id
);
return result.IsSuccess ? Result.FromSuccess() : Result.FromError(result);
}
}