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    this.clazz = clazz;
041  }
042
043  /**
044   * Used to add a consumer for this callback.
045   * @param consumer The consumer to add for this callback. This is an implementation of the
046   *                 {@link Function} interface, which accepts an {@link Callback} parameter and
047   *                 returns a boolean value, which indicates if the "event" should be cancelled or
048   *                 not.
049   */
050  public void addConsumer(final Function<Callback, Boolean> consumer) {
051
052    consumers.add(consumer);
053  }
054
055  /**
056   * Used to call all the consumers for this callback.
057   * @param callback The callback class for this consumer.
058   *
059   * @return This returns a boolean value, which equates to whether this event is cancelled or not.
060   */
061  public boolean call(final Callback callback) {
062    if(!clazz.isInstance(callback)) {
063      return false;
064    }
065
066    boolean cancelled = false;
067    for(Function<Callback, Boolean> consumer : consumers) {
068      if(consumer.apply(callback)) {
069        cancelled = true;
070      }
071    }
072    return cancelled;
073  }
074}