/*
 * Licensed to CRATE Technology GmbH ("Crate") under one or more contributor
 * license agreements.  See the NOTICE file distributed with this work for
 * additional information regarding copyright ownership.  Crate licenses
 * this file to you under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.  You may
 * obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations
 * under the License.
 *
 * However, if you have executed another commercial license agreement
 * with Crate these terms will supersede the license and you may use the
 * software solely pursuant to the terms of the relevant commercial agreement.
 */

package io.crate.executor.task;

import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import io.crate.executor.Task;
import io.crate.operator.operations.ImplementationSymbolVisitor;
import io.crate.operator.operations.merge.MergeOperation;
import io.crate.planner.node.MergeNode;
import org.cratedb.Constants;
import org.elasticsearch.threadpool.ThreadPool;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * merging rows locally on the handler
 */
public class LocalMergeTask implements Task<Object[][]> {

    private final MergeNode mergeNode;
    private final ImplementationSymbolVisitor symbolVisitor;
    private final ThreadPool threadPool;
    private final SettableFuture<Object[][]> result;
    private final List<ListenableFuture<Object[][]>> resultList;

    private List<ListenableFuture<Object[][]>> upstreamResults;

    /**
     *
     * @param implementationSymbolVisitor symbol visitor (on cluster level)
     * @param mergeNode
     */
    public LocalMergeTask(ThreadPool threadPool, ImplementationSymbolVisitor implementationSymbolVisitor, MergeNode mergeNode) {
        this.threadPool = threadPool;
        this.symbolVisitor = implementationSymbolVisitor;
        this.mergeNode = mergeNode;
        this.result = SettableFuture.create();
        this.resultList = Arrays.<ListenableFuture<Object[][]>>asList(this.result);
    }

    /**
     * only operate if we have an upstream as data always comes in via upstream results
     *
     * start listener for every upStream Result
     * if last listener is done he sets the local result.
     */
    @Override
    public void start() {
        if (upstreamResults != null) {
            final MergeOperation mergeOperation = new MergeOperation(symbolVisitor, mergeNode);
            final AtomicInteger countDown = new AtomicInteger(upstreamResults.size());
            for (final ListenableFuture<Object[][]> upStreamResult : upstreamResults) {
                upStreamResult.addListener(new Runnable() {
                    @Override
                    public void run() {
                        Object[][] upstreamResult;
                        try {
                            upstreamResult = upStreamResult.get();
                        } catch (Exception e) {
                            result.setException(e.getCause());
                            return;
                        };
                        mergeOperation.addRows(upstreamResult);
                        if (countDown.decrementAndGet()==0) {
                            result.set(mergeOperation.result());
                        }
                    }
                }, threadPool.executor(ThreadPool.Names.GENERIC));
            }
        } else {
            result.set(Constants.EMPTY_RESULT);
        }
    }

    @Override
    public List<ListenableFuture<Object[][]>> result() {
        return resultList;
    }

    @Override
    public void upstreamResult(List<ListenableFuture<Object[][]>> result) {
        upstreamResults = result;
    }
}

@@ -1047,16 +1047,141 @@
 .task;%0A%0A
+import com.google.common.base.Function;%0Aimport com.google.common.base.Joiner;%0Aimport com.google.common.collect.Collections2;%0A
 import c
@@ -1512,16 +1512,115 @@
 stants;%0A
+import org.elasticsearch.common.logging.ESLogger;%0Aimport org.elasticsearch.common.logging.Loggers;%0A
 import o
@@ -1660,16 +1660,50 @@
 dPool;%0A%0A
+import javax.annotation.Nullable;%0A
 import j
@@ -1899,16 +1899,84 @@
 %5D%5B%5D%3E %7B%0A%0A
+    private final ESLogger logger = Loggers.getLogger(getClass());%0A%0A
     priv
@@ -3545,20 +3545,91 @@
 ject%5B%5D%5B%5D
+ rows;%0A                        try %7B%0A                            rows =
  up
-s
+S
 treamRes
@@ -3627,24 +3627,30 @@
 StreamResult
+.get()
 ;%0A          
@@ -3667,80 +3667,756 @@
     
-try %7B%0A                            upstreamResult = upStreamResult.get();
+    if (logger.isTraceEnabled()) %7B%0A                                String result = Joiner.on(%22, %22).join(Collections2.transform(Arrays.asList(rows),%0A                                        new Function%3CObject%5B%5D, String%3E() %7B%0A                                            @Nullable%0A                                            @Override%0A                                            public String apply(@Nullable Object%5B%5D input) %7B%0A                                                return Arrays.toString(input);%0A                                            %7D%0A                                        %7D)%0A                                );%0A                                logger.trace(String.format(%22received result: %25s%22, result));%0A                            %7D%0A
 %0A   
@@ -4584,17 +4584,16 @@
        %7D
-;
 %0A       
@@ -4636,24 +4636,37 @@
 ows(
-upstreamResult);
+rows); // TODO: apply timeout
 %0A   

add helpful trace output to LocalMergeTask