//
// ClientNostaleClient.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 NosSmooth.Comms.Data;
using NosSmooth.Comms.Data.Messages;
using NosSmooth.Core.Client;
using NosSmooth.Core.Commands;
using NosSmooth.Core.Contracts;
using NosSmooth.Packets;
using NosSmooth.PacketSerializer.Abstractions.Attributes;
using Remora.Results;
namespace NosSmooth.Comms.Core;
///
/// A NosTale client using .
///
public class ClientNostaleClient : INostaleClient
{
private readonly ConnectionHandler _connection;
///
/// Initializes a new instance of the class.
///
/// The connection handler.
public ClientNostaleClient
(ConnectionHandler connection)
{
_connection = connection;
}
///
public Task RunAsync(CancellationToken stopRequested = default)
{
_connection.StartHandler(stopRequested);
return Task.FromResult(Result.FromSuccess());
}
///
public async Task SendPacketAsync(IPacket packet, CancellationToken ct = default)
{
var messageResponse = await _connection.ContractSendMessage
(new PacketMessage(PacketSource.Client, packet))
.WaitForAsync(DefaultStates.ResponseObtained, ct: ct);
return messageResponse.IsSuccess ? messageResponse.Entity : Result.FromError(messageResponse);
}
///
public async Task SendPacketAsync(string packetString, CancellationToken ct = default)
{
var messageResponse = await _connection.ContractSendMessage
(new RawPacketMessage(PacketSource.Client, packetString))
.WaitForAsync(DefaultStates.ResponseObtained, ct: ct);
return messageResponse.IsSuccess ? messageResponse.Entity : Result.FromError(messageResponse);
}
///
public async Task ReceivePacketAsync(string packetString, CancellationToken ct = default)
{
var messageResponse = await _connection.ContractSendMessage
(new RawPacketMessage(PacketSource.Server, packetString))
.WaitForAsync(DefaultStates.ResponseObtained, ct: ct);
return messageResponse.IsSuccess ? messageResponse.Entity : Result.FromError(messageResponse);
}
///
public async Task ReceivePacketAsync(IPacket packet, CancellationToken ct = default)
{
var messageResponse = await _connection.ContractSendMessage
(new PacketMessage(PacketSource.Server, packet))
.WaitForAsync(DefaultStates.ResponseObtained, ct: ct);
return messageResponse.IsSuccess ? messageResponse.Entity : Result.FromError(messageResponse);
}
///
public async Task SendCommandAsync(ICommand command, CancellationToken ct = default)
{
var messageResponse = await _connection.ContractSendMessage
(new CommandMessage(command))
.WaitForAsync(DefaultStates.ResponseObtained, ct: ct);
return messageResponse.IsSuccess ? messageResponse.Entity : Result.FromError(messageResponse);
}
}