/*
 * cc.redberry.pipe: java library for implementation of concurrent pipelines
 * Copyright (c) 2010-2012
 * Bolotin Dmitriy <bolotin.dmitriy@gmail.com>
 *
 * This program is free software: you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation, either version 3 of the License, or (at your option)
 * any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package cc.redberry.pipe.util;

import cc.redberry.pipe.OutputPortCloseable;
import cc.redberry.pipe.InputPort;
import cc.redberry.pipe.OutputPort;

import java.util.concurrent.atomic.AtomicBoolean;

/**
 * T-branch like element putting each taken from OutputPort object into InputPort and propagating it forward by it's
 * take method.
 *
 * @author Bolotin Dmitriy (bolotin.dmitriy@gmail.com)
 */
public class TBranchOutputPort<T> implements OutputPortCloseable<T> {
    private final InputPort<? super T> inputPort;
    private final OutputPort<? extends T> outputPort;
    private final AtomicBoolean closed = new AtomicBoolean(false);

    public TBranchOutputPort(InputPort<? super T> inputPort, OutputPort<? extends T> outputPort) {
        this.inputPort = inputPort;
        this.outputPort = outputPort;
    }

    public static <T> TBranchOutputPort<T> wrap(InputPort<? super T> inputPort, OutputPort<? extends T> outputPort) {
        return new TBranchOutputPort<T>(inputPort, outputPort);
    }

    @Override
    public T take() {
        if (closed.get())
            return null;
        T object = outputPort.take();
        if (object == null) {
            if (closed.compareAndSet(false, true))
                inputPort.put(null);
        } else
            inputPort.put(object);

        return object;
    }

    @Override
    public void close() {
        if (outputPort instanceof OutputPortCloseable)
            ((OutputPortCloseable) outputPort).close();

        if (closed.compareAndSet(false, true))
            inputPort.put(null);
    }
}
