using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tango.Logging;
using Tango.PMR.Common;
using Tango.Core.Commands;
using Tango.Transport;
using Tango.Core;
namespace Tango.Emulations
{
///
/// Represents an base class.
///
///
///
public abstract class EmulatorBase : ExtendedObject, IEmulator
{
#region Properties
private bool _isStarted;
///
/// Gets or sets a value indicating whether the emulator is started.
///
public bool IsStarted
{
get { return _isStarted; }
set { _isStarted = value; RaisePropertyChanged(nameof(IsStarted)); InvalidateRelayCommands(); }
}
private ITransporter _transporter;
///
/// Gets or sets the transporter.
///
public ITransporter Transporter
{
get { return _transporter; }
set
{
_transporter = value;
SetTransporter(_transporter);
}
}
#endregion
#region Commands
///
/// Gets or sets the start command.
///
public RelayCommand StartCommand { get; set; }
///
/// Gets or sets the stop command.
///
public RelayCommand StopCommand { get; set; }
#endregion
#region Constructors
///
/// Initializes a new instance of the class.
///
public EmulatorBase()
{
StartCommand = new RelayCommand(async () => { await Start(); }, (x) => !IsStarted);
StopCommand = new RelayCommand(async () => { await Stop(); }, (x) => IsStarted);
}
///
/// Initializes a new instance of the class.
///
/// The transporter.
public EmulatorBase(ITransporter transporter) : this()
{
Transporter = transporter;
}
#endregion
#region Private Methods
///
/// Sets the transporter.
///
/// The transporter.
private void SetTransporter(ITransporter transporter)
{
if (_transporter != null)
{
_transporter.StateChanged -= OnTransporterStateChanged;
}
_transporter = transporter;
_transporter.RequestReceived += OnTransporterRequestReceived;
_transporter.StateChanged += OnTransporterStateChanged;
}
#endregion
#region Public Methods
///
/// Stops this instance.
///
public virtual async Task Stop()
{
if (IsStarted)
{
await _transporter.Disconnect();
IsStarted = false;
}
}
///
/// Starts this instance.
///
public virtual async Task Start()
{
if (!IsStarted)
{
await _transporter.Connect();
IsStarted = true;
}
}
#endregion
#region Virtual Methods
///
/// Called when transporter state has changed.
///
/// The sender.
/// The e.
protected virtual void OnTransporterStateChanged(object sender, TransportComponentState e)
{
LogManager.Log("Transporter state changed: " + e.ToString());
}
#endregion
#region Abstract Methods
///
/// Called on new request message.
///
/// The sender.
/// The container.
protected abstract void OnTransporterRequestReceived(object sender, RequestReceivedEventArgs e);
#endregion
#region Dispose
///
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
///
public void Dispose()
{
Stop().Wait();
if (Transporter != null) Transporter.Dispose();
}
#endregion
}
}