001package net.tnemc.plugincore.core.api;
002/*
003 * The New Plugin Core
004 * Copyright (C) 2022 - 2024 Daniel "creatorfromhell" Vidmar
005 *
006 * This program is free software: you can redistribute it and/or modify
007 * it under the terms of the GNU Affero General Public License as published by
008 * the Free Software Foundation, either version 3 of the License, or
009 * (at your option) any later version.
010 *
011 * This program is distributed in the hope that it will be useful,
012 * but WITHOUT ANY WARRANTY; without even the implied warranty of
013 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
014 * GNU Affero General Public License for more details.
015 *
016 * You should have received a copy of the GNU Affero General Public License
017 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
018 */
019
020
021import net.tnemc.plugincore.core.api.callback.Callback;
022
023import java.util.ArrayList;
024import java.util.List;
025import java.util.function.Function;
026
027/**
028 * CallbackEntry represents a class that serves as an entry for a specific callback.
029 *
030 * @author creatorfromhell
031 * @since 0.1.2.0
032 */
033public class CallbackEntry {
034
035  private final List<Function<Callback, Boolean>> consumers = new ArrayList<>();
036
037  private final Class<? extends Callback> clazz;
038
039  public CallbackEntry(Class<? extends Callback> clazz) {
040
041    this.clazz = clazz;
042  }
043
044  /**
045   * Used to add a consumer for this callback.
046   *
047   * @param consumer The consumer to add for this callback. This is an implementation of the
048   *                 {@link Function} interface, which accepts an {@link Callback} parameter and
049   *                 returns a boolean value, which indicates if the "event" should be cancelled or
050   *                 not.
051   */
052  public void addConsumer(final Function<Callback, Boolean> consumer) {
053
054    consumers.add(consumer);
055  }
056
057  /**
058   * Used to call all the consumers for this callback.
059   *
060   * @param callback The callback class for this consumer.
061   *
062   * @return This returns a boolean value, which equates to whether this event is cancelled or not.
063   */
064  public boolean call(final Callback callback) {
065
066    if(!clazz.isInstance(callback)) {
067      return false;
068    }
069
070    boolean cancelled = false;
071    for(Function<Callback, Boolean> consumer : consumers) {
072      if(consumer.apply(callback)) {
073        cancelled = true;
074      }
075    }
076    return cancelled;
077  }
078}