001// Copyright (c) FIRST and other WPILib contributors.
002// Open Source Software; you can modify and/or share it under the terms of
003// the WPILib BSD license file in the root directory of this project.
004
005package edu.wpi.first.wpilibj2.command;
006
007import java.util.Set;
008
009/**
010 * Schedules the given commands when this command is initialized, and ends when all the commands are
011 * no longer scheduled. Useful for forking off from CommandGroups. If this command is interrupted,
012 * it will cancel all of the commands.
013 */
014public class ProxyScheduleCommand extends CommandBase {
015  private final Set<Command> m_toSchedule;
016  private boolean m_finished;
017
018  /**
019   * Creates a new ProxyScheduleCommand that schedules the given commands when initialized, and ends
020   * when they are all no longer scheduled.
021   *
022   * @param toSchedule the commands to schedule
023   */
024  public ProxyScheduleCommand(Command... toSchedule) {
025    m_toSchedule = Set.of(toSchedule);
026  }
027
028  @Override
029  public void initialize() {
030    for (Command command : m_toSchedule) {
031      command.schedule();
032    }
033  }
034
035  @Override
036  public void end(boolean interrupted) {
037    if (interrupted) {
038      for (Command command : m_toSchedule) {
039        command.cancel();
040      }
041    }
042  }
043
044  @Override
045  public void execute() {
046    m_finished = true;
047    for (Command command : m_toSchedule) {
048      m_finished &= !command.isScheduled();
049    }
050  }
051
052  @Override
053  public boolean isFinished() {
054    return m_finished;
055  }
056}