001// Copyright (c) Choreo contributors
002
003package choreo.util;
004
005import edu.wpi.first.wpilibj.Alert;
006import edu.wpi.first.wpilibj.Alert.AlertType;
007import java.util.ArrayList;
008import java.util.List;
009import java.util.function.Function;
010
011/** A utility class for creating alerts under the "Choreo Alerts" group. */
012public class ChoreoAlert {
013  /**
014   * Creates an alert under the "Choreo" group.
015   *
016   * @param name The name of the alert
017   * @param type The type of alert
018   * @return an Alert published under the "Choreo" group
019   */
020  public static Alert alert(String name, AlertType type) {
021    return new Alert("Choreo Alerts", name, type);
022  }
023
024  /**
025   * Creates a {@link MultiAlert} under the "Choreo" group.
026   *
027   * @param textGenerator A function that accepts a list of causes and returns an alert message
028   * @param type The type of alert
029   * @return a MultiAlert published under the "Choreo" group
030   */
031  public static MultiAlert multiAlert(
032      Function<List<String>, String> textGenerator, AlertType type) {
033    return new MultiAlert(textGenerator, type);
034  }
035
036  /**
037   * An alert that can have multiple causes. Utilizes a function to generate an error message from a
038   * list of causes.
039   */
040  public static class MultiAlert extends Alert {
041    private final Function<List<String>, String> textGenerator;
042    private final List<String> causes = new ArrayList<>();
043
044    MultiAlert(Function<List<String>, String> textGenerator, AlertType type) {
045      super("Choreo Alerts", textGenerator.apply(List.of()), type);
046      this.textGenerator = textGenerator;
047    }
048
049    /**
050     * Adds an error causer to this alert, and pushes the alert to NetworkTables if it is not
051     * already present.
052     *
053     * @param name The name of the error causer
054     */
055    public void addCause(String name) {
056      causes.add(name);
057      setText(textGenerator.apply(causes));
058      set(true);
059    }
060  }
061
062  /** Factory class. */
063  private ChoreoAlert() {}
064}