using System; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace MonoDevelop.ConnectedServices { /// /// Represents a set of code dependencies that are added to the project. /// public sealed class GroupedCodeDependency : ConnectedServiceDependency { readonly GroupedDependencyKind kind; readonly ConnectedServiceDependency [] dependencies; /// /// Initializes a new instance of the class. /// public GroupedCodeDependency (IConnectedService service, string displayName, GroupedDependencyKind kind, params ConnectedServiceDependency[] dependencies) : base (service, ConnectedServiceDependency.CodeDependencyCategory, displayName) { if (dependencies.Any (x => x.Category != ConnectedServiceDependency.CodeDependencyCategory)) { throw new ArgumentException ("All dependencies in a group must be Code dependencies", nameof (dependencies)); } this.kind = kind; this.dependencies = dependencies; } /// /// Adds the dependency to the project and returns true if the dependency was added to the project /// protected override async Task OnAddToProject (CancellationToken token) { if (this.dependencies.Length == 0) { return true; } switch (this.kind) { case GroupedDependencyKind.All: bool added = true; foreach (var dependency in this.dependencies) { added &= await dependency.AddToProject (token).ConfigureAwait (false); } return added; case GroupedDependencyKind.Any: foreach (var dependency in this.dependencies) { if (await dependency.AddToProject (token).ConfigureAwait (false)) { return true; } } return false; default: throw new NotSupportedException (string.Format ("Unsupported GroupedDependencyKind {0}", this.kind)); } } /// /// Gets a value indicating whether this is added to the project or not. /// public override bool IsAdded { get { switch (this.kind) { case GroupedDependencyKind.All: return this.dependencies.All (x => x.Status == Status.Added); case GroupedDependencyKind.Any: return this.dependencies.Any (x => x.Status == Status.Added); default: throw new NotSupportedException (string.Format ("Unsupported GroupedDependencyKind {0}", this.kind)); } } } /// /// Removes the dependency from the project /// protected override async Task OnRemoveFromProject (CancellationToken token) { if (this.dependencies.Length == 0) { return true; } var result = true; foreach (var dependency in this.dependencies.Reverse ()) { if (dependency.Status == Status.Added) { if (!await dependency.RemoveFromProject (token).ConfigureAwait (false)) { result = false; } } } return result; } } }