using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using MultiTerm.Protocols.Types;
namespace MultiTerm.Protocols;
///
/// Class that represents all connection and usage settings for a specific .
/// Can be bound to UI using MVVM pattern.
/// Implementing class must also implement ! Otherwise does not work.
///
public abstract partial class ProtocolSettingsViewModel : ObservableObject, IProtocolSettingsViewModel
{
private const string connectedStateButtonText = "Disconnect";
private const string disconnectedStateButtonText = "Connect";
protected readonly IMessenger messenger;
public event EventHandler? ConnectRequested;
public event EventHandler? DisconnectRequested;
public abstract ProtocolType ProtocolType { get; }
///
/// Indicates wether the settings can currently be edited.
/// Initially are editable
///
public bool AreEditable = true;
[ObservableProperty]
private string connectDisconnectButtonText = disconnectedStateButtonText;
public ProtocolSettingsViewModel(IMessenger messenger)
{
this.messenger = messenger;
}
///
/// Binding to Connect/Disconnect button.
/// Button text is provided in
/// Implementing class must also implement ! Otherwise does not work.
///
[RelayCommand(AllowConcurrentExecutions = false)]
private async Task ConnectDisconnectAsync()
{
await Task.Factory.StartNew(() =>
{
// if currently disconnected
if (this.ConnectDisconnectButtonText == disconnectedStateButtonText)
{
// CONNECT
this.AreEditable = false;
this.ConnectRequested?.Invoke(this, (IProtocolSettings)this); // implementing class must also implement IProtocolSettings!
this.ConnectDisconnectButtonText = connectedStateButtonText;
}
// if currently connected
else if (this.ConnectDisconnectButtonText == connectedStateButtonText)
{
// DISCONNECT
this.DisconnectRequested?.Invoke(this, EventArgs.Empty);
this.ConnectDisconnectButtonText = disconnectedStateButtonText;
this.AreEditable = true;
}
else
{
throw new Exception($"'{nameof(ConnectDisconnectAsync)}()' has not recognized button text, cannot identify state of connection.");
}
});
}
}