using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Tango.Core; namespace Tango.FSE.Common.RemoteUpgrade { public class RemoteUpgradeHandler : ExtendedObject { private Action _abortAction; private TaskCompletionSource _completionSource; public event EventHandler StatusChanged; public event EventHandler> ProgressChanged; internal bool IsAborted { get; private set; } public bool CanAbort { get; internal set; } = true; private TangoProgress _progress; public TangoProgress Progress { get { return _progress; } set { _progress = value; RaisePropertyChangedAuto(); } } private RemoteUpgradeHandlerStatus _status; public RemoteUpgradeHandlerStatus Status { get { return _status; } set { if (_status != value) { _status = value; RaisePropertyChangedAuto(); StatusChanged?.Invoke(this, value); } } } private Exception _failedException; public Exception FailedException { get { return _failedException; } set { _failedException = value; RaisePropertyChangedAuto(); } } public RemoteUpgradeHandler() { Progress = new TangoProgress() { Message = "Initializing...", Maximum = 100, }; _completionSource = new TaskCompletionSource(); } public RemoteUpgradeHandler(String message) : this() { Progress.Message = message; Progress.Maximum = 100; } internal RemoteUpgradeHandler(Action abortAction) : this() { _abortAction = abortAction; } internal void UpdateProgress(String message, bool isIndeterminate = true, double progress = 0, double maximum = 100) { UpdateProgress(new TangoProgress() { Value = progress, Maximum = maximum, IsIndeterminate = isIndeterminate, Message = message, }); } internal void UpdateProgress(TangoProgress progress) { Progress = progress; ProgressChanged?.Invoke(this, new TangoProgressChangedEventArgs() { Progress = Progress }); } public void Abort() { IsAborted = true; _abortAction?.Invoke(); } public Task WaitForCompletion() { return _completionSource.Task; } internal void RaiseFailed(Exception exception) { FailedException = exception; Status = RemoteUpgradeHandlerStatus.Failed; CanAbort = true; _completionSource.SetException(exception); } internal void RaiseCompleted() { Status = RemoteUpgradeHandlerStatus.Completed; CanAbort = true; _completionSource.SetResult(Status); } internal void RaiseAborted() { Status = RemoteUpgradeHandlerStatus.Aborted; CanAbort = true; _completionSource.SetException(new OperationCanceledException("Remote upgrade operation aborted.")); } } }