using System;
using System.ComponentModel;
using System.Deployment.Application;
using System.Threading;
using System.Threading.Tasks;
namespace MediaBrowser.ClickOnce
{
    /// 
    /// Class ApplicationUpdater
    /// 
    public class ApplicationUpdater
    {
        /// 
        /// The _task completion source
        /// 
        private TaskCompletionSource _taskCompletionSource;
        /// 
        /// The _progress
        /// 
        private IProgress _progress;
        /// 
        /// Updates the application
        /// 
        /// The cancellation token.
        /// The progress.
        /// Task{AsyncCompletedEventArgs}.
        /// Current deployment is not network deployed.
        public Task UpdateApplication(CancellationToken cancellationToken, IProgress progress)
        {
            if (!ApplicationDeployment.IsNetworkDeployed)
            {
                throw new InvalidOperationException("Current deployment is not network deployed.");
            }
            _progress = progress;
            _taskCompletionSource = new TaskCompletionSource();
            var deployment = ApplicationDeployment.CurrentDeployment;
            cancellationToken.Register(deployment.UpdateAsyncCancel);
            cancellationToken.ThrowIfCancellationRequested();
            deployment.UpdateCompleted += deployment_UpdateCompleted;
            deployment.UpdateProgressChanged += deployment_UpdateProgressChanged;
            deployment.UpdateAsync();
            return _taskCompletionSource.Task;
        }
        /// 
        /// Handles the UpdateCompleted event of the deployment control.
        /// 
        /// The source of the event.
        /// The  instance containing the event data.
        void deployment_UpdateCompleted(object sender, AsyncCompletedEventArgs e)
        {
            var deployment = ApplicationDeployment.CurrentDeployment;
            deployment.UpdateCompleted -= deployment_UpdateCompleted;
            deployment.UpdateProgressChanged -= deployment_UpdateProgressChanged;
            if (e.Error != null)
            {
                _taskCompletionSource.SetException(e.Error);
            }
            else if (e.Cancelled)
            {
                _taskCompletionSource.SetCanceled();
            }
            else
            {
                _taskCompletionSource.SetResult(e);
            }
        }
        /// 
        /// Handles the UpdateProgressChanged event of the deployment control.
        /// 
        /// The source of the event.
        /// The  instance containing the event data.
        void deployment_UpdateProgressChanged(object sender, DeploymentProgressChangedEventArgs e)
        {
            _progress.Report(e.ProgressPercentage);
        }
    }
}