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
020import net.tnemc.plugincore.core.api.callback.Callback;
021
022import java.util.HashMap;
023import java.util.Map;
024import java.util.function.Function;
025
026/**
027 * CallbackManager used to manage specific callbacks.
028 *
029 * @author creatorfromhell
030 * @since 0.1.2.0
031 */
032public class CallbackManager {
033
034  protected final Map<String, CallbackEntry> callbacks = new HashMap<>();
035
036  public CallbackManager(final CallbackProvider provider) {
037
038    provider.init(this);
039    initDefaultCallbacks();
040  }
041
042  protected void initDefaultCallbacks() {
043
044  }
045
046  /**
047   * Used to add a new callback into the system.
048   *
049   * @param identifier The identifier of the callback to add.
050   * @param entry      The {@link CallbackEntry}, which manages the consumers.
051   */
052  public void addCallback(final String identifier, CallbackEntry entry) {
053
054    this.callbacks.put(identifier, entry);
055  }
056
057  /**
058   * Used to add a consumer for this callback.
059   *
060   * @param name     The name of the callback to attach this consumer to.
061   * @param consumer The consumer to add for this callback. This is an implementation of the
062   *                 {@link Function} interface, which accepts an {@link Callback} parameter and
063   *                 returns a boolean value, which indicates if the "event" should be cancelled or
064   *                 not.
065   */
066  public void addConsumer(final String name, Function<Callback, Boolean> consumer) {
067
068    if(this.callbacks.containsKey(name)) {
069      this.callbacks.get(name).addConsumer(consumer);
070    }
071  }
072
073  /**
074   * Used to call all the consumers for this callback.
075   *
076   * @param callback The callback class for this consumer.
077   *
078   * @return This returns a boolean value, which equates to whether this event is cancelled or not.
079   */
080  public boolean call(Callback callback) {
081
082    if(this.callbacks.containsKey(callback.name())) {
083      return this.callbacks.get(callback.name()).call(callback);
084    }
085    return false;
086  }
087}