001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2016-2026 Michael N. Lipp
004 * 
005 * This program is free software; you can redistribute it and/or modify it 
006 * under the terms of the GNU Affero General Public License as published by 
007 * the Free Software Foundation; either version 3 of the License, or 
008 * (at your option) any later version.
009 * 
010 * This program is distributed in the hope that it will be useful, but 
011 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
012 * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License 
013 * for more details.
014 * 
015 * You should have received a copy of the GNU Affero General Public License along 
016 * with this program; if not, see <http://www.gnu.org/licenses/>.
017 */
018
019package org.jgrapes.core;
020
021import org.jgrapes.core.internal.EventBase;
022
023/**
024 * A base class for events that signal the completion of some other
025 * (monitored) event and provide this other event as their result. 
026 * Events of this type are automatically fired when the framework
027 * detects that the monitored event has completed.  
028 * 
029 * Use {@link #event()} to conveniently access the monitored event 
030 * while handling the completion event. 
031 * 
032 * @see EventBase#onCompletion(Event, java.util.function.Consumer)
033 * @see EventBase#addCompletionEvent(Event)
034 */
035public abstract class CompletionEvent<T extends Event<?>>
036        extends Event<T> {
037
038    /**
039     * Instantiates a new completion event.
040     *
041     * @param monitoredEvent the monitored event
042     * @param channels the channels
043     */
044    @SuppressWarnings("PMD.ConstructorCallsOverridableMethod")
045    public CompletionEvent(T monitoredEvent, Channel... channels) {
046        super(channels);
047        setResult(monitoredEvent);
048        monitoredEvent.addCompletionEvent(this);
049    }
050
051    /**
052     * Return the completed event. This is simply a shortcut 
053     * for ``currentResults().get(0)``.
054     * 
055     * @return the completed event
056     */
057    public T event() {
058        return currentResults().get(0);
059    }
060
061    /*
062     * (non-Javadoc)
063     * 
064     * @see java.lang.Object#toString()
065     */
066    @Override
067    public String toString() {
068        StringBuilder builder = new StringBuilder();
069        builder.append(Components.className(getClass()))
070            .append('(')
071            .append(Components.objectName(currentResults().get(0)))
072            .append(") [");
073        if (channels().length > 0) {
074            builder.append("channels=").append(Channel.toString(channels()));
075        }
076        builder.append(']');
077        return builder.toString();
078    }
079}