// Copyright (C) 2011 - Will Glozer.  All rights reserved.

package com.lambdaworks.redis.output;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

import com.lambdaworks.redis.RedisCommandExecutionException;
import com.lambdaworks.redis.codec.RedisCodec;
import com.lambdaworks.redis.protocol.CommandOutput;
import com.lambdaworks.redis.protocol.RedisCommand;

/**
 * Output of all commands within a MULTI block.
 * 
 * @param <K> Key type.
 * @param <V> Value type.
 * @author Will Glozer
 */
public class MultiOutput<K, V> extends CommandOutput<K, V, List<Object>> {
    private final Queue<RedisCommand<K, V, ?>> queue;

    public MultiOutput(RedisCodec<K, V> codec) {
        super(codec, new ArrayList<Object>());
        queue = new LinkedList<RedisCommand<K, V, ?>>();
    }

    public void add(RedisCommand<K, V, ?> cmd) {
        queue.add(cmd);
    }

    public void cancel() {
        for (RedisCommand<K, V, ?> c : queue) {
            c.complete();
        }
    }

    @Override
    public void set(long integer) {
        queue.peek().getOutput().set(integer);
    }

    @Override
    public void set(ByteBuffer bytes) {
        queue.peek().getOutput().set(bytes);
    }

    @Override
    public void setError(ByteBuffer error) {
        CommandOutput<K, V, ?> output = queue.isEmpty() ? this : queue.peek().getOutput();
        output.setError(decodeAscii(error));
    }

    @Override
    public void complete(int depth) {
        if (depth == 1) {
            RedisCommand<K, V, ?> cmd = queue.remove();
            CommandOutput<K, V, ?> o = cmd.getOutput();
            output.add(!o.hasError() ? o.get() : new RedisCommandExecutionException(o.getError()));
            cmd.complete();
        } else if (depth == 0 && !queue.isEmpty()) {
            for (RedisCommand<K, V, ?> cmd : queue) {
                cmd.complete();
            }
        }
    }
}

@@ -1114,36 +1114,151 @@
 ) %7B%0A        
-queue.peek()
+RedisCommand%3CK, V, ?%3E command = queue.peek();%0A        if (command != null && command.getOutput() != null) %7B%0A            command
 .getOutput()
@@ -1272,16 +1272,26 @@
 teger);%0A
+        %7D%0A
     %7D%0A%0A 
@@ -1351,28 +1351,143 @@
         
-queue.peek()
+RedisCommand%3CK, V, ?%3E command = queue.peek();%0A        if (command != null && command.getOutput() != null) %7B%0A            command
 .getOutp
@@ -1503,16 +1503,26 @@
 bytes);%0A
+        %7D%0A
     %7D%0A%0A 
@@ -1770,24 +1770,86 @@
 nt depth) %7B%0A
+        if (queue.isEmpty()) %7B%0A            return;%0A        %7D%0A%0A
         if (

Fix NPE in MultiOutput when nested Output is null #20