using System; using MtApi.Monitors.Triggers; namespace MtApi.Monitors { public abstract class MtMonitorBase { #region Fields private volatile bool _isStarted = false; private bool _syncTrigger; #endregion #region Properties /// /// ApiClient /// protected MtApiClient ApiClient { get; } /// /// Returns true if the is connected. /// public bool IsMtConnected => ApiClient.ConnectionState == MtConnectionState.Connected; /// /// Returns the trigger which will be used to raise the monitoring call. /// public IMonitorTrigger MonitorTrigger { get; } /// /// Returns true if the Monitor is started. /// public bool IsStarted { get => _isStarted; } /// /// If true, the will be stopped or started automatically when or will be called. /// CAUTION: If you use the MonitorTrigger for different Monitors, this will stop all monitors if you call stop and is true. /// public bool SyncTrigger { get => _syncTrigger; set => _syncTrigger = value; } #endregion #region ctor /// /// Default constructor for Monitors /// /// The apiClient which will be used to work with. /// The trigger which lead this Monitor to do his work. /// See property . public MtMonitorBase(MtApiClient apiClient, IMonitorTrigger monitorTrigger, bool syncTrigger = false) { ApiClient = apiClient ?? throw new ArgumentNullException(nameof(apiClient)); MonitorTrigger = monitorTrigger ?? throw new ArgumentNullException(nameof(monitorTrigger)); SyncTrigger = syncTrigger; } #endregion #region Methods /// /// Let the monitor listen to the . /// public virtual void Start() { if (!_isStarted) { ApiClient.ConnectionStateChanged += ApiClientConnectionStateChanged; MonitorTrigger.Raised += MonitorTriggerRaised; _isStarted = true; OnStart(); if (SyncTrigger) MonitorTrigger.Start(); } } /// /// Let the monitor stop listening to the . /// public virtual void Stop() { if (_isStarted) { MonitorTrigger.Raised -= MonitorTriggerRaised; ApiClient.ConnectionStateChanged -= ApiClientConnectionStateChanged; _isStarted = false; OnStop(); if (SyncTrigger) MonitorTrigger.Stop(); } } private void MonitorTriggerRaised(object? sender, EventArgs e) => OnTriggerRaised(); private void ApiClientConnectionStateChanged(object? sender, MtConnectionEventArgs e) { if (e.Status == MtConnectionState.Connected) OnMtConnected(); else if (e.Status == MtConnectionState.Failed || e.Status == MtConnectionState.Disconnected) OnMtDisconnected(); } /// /// Will be called when will be called. /// protected virtual void OnStart() { } /// /// Will be called when will be called. /// protected virtual void OnStop() { } /// /// Will be called when the is successfully connected. /// protected virtual void OnMtConnected() { } /// /// Will be called when is disconnected. /// protected virtual void OnMtDisconnected() { } /// /// Will be called when the raised. /// protected abstract void OnTriggerRaised(); #endregion } }