001/*
002 * JGrapes Event Driven Framework
003 * Copyright (C) 2016-2018 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 completion events that use the completed event
025 * as their result type. Use {@link #event()} to access
026 * the completed event while handling the completion event. 
027 * 
028 * @see EventBase#onCompletion(Event, java.util.function.Consumer)
029 */
030public abstract class CompletionEvent<T extends Event<?>>
031        extends Event<T> {
032
033    /**
034     * Instantiates a new completion event.
035     *
036     * @param monitoredEvent the monitored event
037     * @param channels the channels
038     */
039    public CompletionEvent(T monitoredEvent, Channel... channels) {
040        super(channels);
041        setResult(monitoredEvent);
042        monitoredEvent.addCompletionEvent(this);
043    }
044
045    /**
046     * Return the completed event. This is simply a shortcut 
047     * for ``currentResults().get(0)``.
048     * 
049     * @return the completed event
050     */
051    public T event() {
052        return currentResults().get(0);
053    }
054
055    /*
056     * (non-Javadoc)
057     * 
058     * @see java.lang.Object#toString()
059     */
060    @Override
061    public String toString() {
062        StringBuilder builder = new StringBuilder();
063        builder.append(Components.className(getClass()))
064            .append('(')
065            .append(Components.objectName(currentResults().get(0)))
066            .append(") [");
067        if (channels().length > 0) {
068            builder.append("channels=");
069            builder.append(Channel.toString(channels()));
070        }
071        builder.append(']');
072        return builder.toString();
073    }
074}