using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tango.Core; namespace Tango.FSE.Common.Insights { public class InsightsHandler : ExtendedObject { private Action _abortAction; private TaskCompletionSource _completionSource; private bool _completed; public event EventHandler StatusChanged; public event EventHandler> ProgressChanged; public event EventHandler Completed; private InsightsHandlerStatus _status; public InsightsHandlerStatus Status { get { return _status; } set { if (_status != value) { _status = value; RaisePropertyChangedAuto(); StatusChanged?.Invoke(this, _status); } } } private TangoProgress _progress; public TangoProgress Progress { get { return _progress; } set { _progress = value; RaisePropertyChangedAuto(); if (_progress != null) { ProgressChanged?.Invoke(this, new TangoProgressChangedEventArgs(_progress)); } } } private Exception _failedException; public Exception FailedException { get { return _failedException; } set { _failedException = value; RaisePropertyChangedAuto(); } } public InsightsHandler(Action abortAction) { _completionSource = new TaskCompletionSource(); _abortAction = abortAction; Progress = new TangoProgress("Initializing..."); } public void Abort() { if (!_completed) { _completed = true; _abortAction?.Invoke(); Status = InsightsHandlerStatus.Aborted; _completionSource.SetException(new OperationCanceledException()); } } public void RaiseFailed(Exception ex) { if (!_completed) { _completed = true; FailedException = ex; Status = InsightsHandlerStatus.Failed; _completionSource.SetException(ex); } } public void RaiseCompleted(InsightsPackage package) { if (!_completed) { _completed = true; Status = InsightsHandlerStatus.Completed; Completed?.Invoke(this, package); _completionSource.SetResult(package); } } public Task WaitForCompletion() { return _completionSource.Task; } } }