using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Discord.Commands
{
///
/// Provides extension methods for the class.
///
public static class CommandServiceExtensions
{
///
/// Returns commands that can be executed under the current context.
///
/// The set of commands to be checked against.
/// The current command context.
/// The service provider used for dependency injection upon precondition check.
///
/// A read-only collection of commands that can be executed under the current context.
///
public static async Task> GetExecutableCommandsAsync(this ICollection commands, ICommandContext context, IServiceProvider provider)
{
var executableCommands = new List();
var tasks = commands.Select(async c =>
{
var result = await c.CheckPreconditionsAsync(context, provider).ConfigureAwait(false);
return new { Command = c, PreconditionResult = result };
});
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
foreach (var result in results)
{
if (result.PreconditionResult.IsSuccess)
executableCommands.Add(result.Command);
}
return executableCommands;
}
///
/// Returns commands that can be executed under the current context.
///
/// The desired command service class to check against.
/// The current command context.
/// The service provider used for dependency injection upon precondition check.
///
/// A read-only collection of commands that can be executed under the current context.
///
public static Task> GetExecutableCommandsAsync(this CommandService commandService, ICommandContext context, IServiceProvider provider)
=> GetExecutableCommandsAsync(commandService.Commands.ToArray(), context, provider);
///
/// Returns commands that can be executed under the current context.
///
/// The module to be checked against.
/// The current command context.
/// The service provider used for dependency injection upon precondition check.
///
/// A read-only collection of commands that can be executed under the current context.
///
public static async Task> GetExecutableCommandsAsync(this ModuleInfo module, ICommandContext context, IServiceProvider provider)
{
var executableCommands = new List();
executableCommands.AddRange(await module.Commands.ToArray().GetExecutableCommandsAsync(context, provider).ConfigureAwait(false));
var tasks = module.Submodules.Select(async s => await s.GetExecutableCommandsAsync(context, provider).ConfigureAwait(false));
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
executableCommands.AddRange(results.SelectMany(c => c));
return executableCommands;
}
}
}