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