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 * Used to add a new callback into the system. 047 * @param identifier The identifier of the callback to add. 048 * @param entry The {@link CallbackEntry}, which manages the consumers. 049 */ 050 public void addCallback(final String identifier, CallbackEntry entry) { 051 this.callbacks.put(identifier, entry); 052 } 053 054 /** 055 * Used to add a consumer for this callback. 056 * @param name The name of the callback to attach this consumer to. 057 * @param consumer The consumer to add for this callback. This is an implementation of the 058 * {@link Function} interface, which accepts an {@link Callback} parameter and 059 * returns a boolean value, which indicates if the "event" should be cancelled or 060 * not. 061 */ 062 public void addConsumer(final String name, Function<Callback, Boolean> consumer) { 063 064 if(this.callbacks.containsKey(name)) { 065 this.callbacks.get(name).addConsumer(consumer); 066 } 067 } 068 069 /** 070 * Used to call all the consumers for this callback. 071 * @param callback The callback class for this consumer. 072 * 073 * @return This returns a boolean value, which equates to whether this event is cancelled or not. 074 */ 075 public boolean call(Callback callback) { 076 077 if(this.callbacks.containsKey(callback.name())) { 078 return this.callbacks.get(callback.name()).call(callback); 079 } 080 return false; 081 } 082}