/*
 * Licensed to Elasticsearch under one or more contributor
 * license agreements. See the NOTICE file distributed with
 * this work for additional information regarding copyright
 * ownership. Elasticsearch 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.
 */
package org.elasticsearch.action.ingest;

import org.elasticsearch.action.Action;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.ActionRequest;
import org.elasticsearch.action.ActionResponse;
import org.elasticsearch.action.bulk.BulkAction;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.index.IndexAction;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.support.ActionFilter;
import org.elasticsearch.action.support.ActionFilterChain;
import org.elasticsearch.cluster.ClusterService;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.common.Randomness;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.node.NodeModule;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportException;
import org.elasticsearch.transport.TransportResponse;
import org.elasticsearch.transport.TransportResponseHandler;
import org.elasticsearch.transport.TransportService;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

public final class IngestProxyActionFilter implements ActionFilter {

    private final ClusterService clusterService;
    private final TransportService transportService;
    private final AtomicInteger randomNodeGenerator = new AtomicInteger(Randomness.get().nextInt());

    @Inject
    public IngestProxyActionFilter(ClusterService clusterService, TransportService transportService) {
        this.clusterService = clusterService;
        this.transportService = transportService;
    }

    @Override
    public void apply(Task task, String action, ActionRequest request, ActionListener listener, ActionFilterChain chain) {
        Action ingestAction;
        switch (action) {
            case IndexAction.NAME:
                ingestAction = IndexAction.INSTANCE;
                IndexRequest indexRequest = (IndexRequest) request;
                if (Strings.hasText(indexRequest.getPipeline())) {
                    forwardIngestRequest(ingestAction, request, listener);
                } else {
                    chain.proceed(task, action, request, listener);
                }
                break;
            case BulkAction.NAME:
                ingestAction = BulkAction.INSTANCE;
                BulkRequest bulkRequest = (BulkRequest) request;
                if (bulkRequest.hasIndexRequestsWithPipelines()) {
                    forwardIngestRequest(ingestAction, request, listener);
                } else {
                    chain.proceed(task, action, request, listener);
                }
                break;
            default:
                chain.proceed(task, action, request, listener);
                break;
        }
    }

    private void forwardIngestRequest(Action action, ActionRequest request, ActionListener listener) {
        transportService.sendRequest(randomIngestNode(), action.name(), request, new TransportResponseHandler<TransportResponse>() {
            @Override
            public TransportResponse newInstance() {
                return action.newResponse();
            }

            @Override
            @SuppressWarnings("unchecked")
            public void handleResponse(TransportResponse response) {
                listener.onResponse(response);
            }

            @Override
            public void handleException(TransportException exp) {
                listener.onFailure(exp);
            }

            @Override
            public String executor() {
                return ThreadPool.Names.SAME;
            }
        });
    }

    @Override
    public void apply(String action, ActionResponse response, ActionListener listener, ActionFilterChain chain) {
        chain.proceed(action, response, listener);
    }

    @Override
    public int order() {
        return Integer.MAX_VALUE;
    }

    private DiscoveryNode randomIngestNode() {
        assert NodeModule.isNodeIngestEnabled(clusterService.localNode().attributes()) == false;
        DiscoveryNode[] ingestNodes = clusterService.state().getNodes().getIngestNodes().values().toArray(DiscoveryNode.class);
        if (ingestNodes.length == 0) {
            throw new IllegalStateException("There are no ingest nodes in this cluster, unable to forward request to an ingest node.");
        }

        int index = getNodeNumber();
        return ingestNodes[(index) % ingestNodes.length];
    }

    private int getNodeNumber() {
        int index = randomNodeGenerator.incrementAndGet();
        if (index < 0) {
            index = 0;
            randomNodeGenerator.set(0);
        }
        return index;
    }
}

@@ -908,24 +908,87 @@
 onListener;%0A
+import org.elasticsearch.action.ActionListenerResponseHandler;%0A
 import org.e
@@ -2660,32 +2660,35 @@
 n, ActionRequest
+%3C?%3E
  request, Action
@@ -2687,32 +2687,35 @@
 , ActionListener
+%3C?%3E
  listener, Actio
@@ -3767,32 +3767,67 @@
        %7D%0A    %7D%0A%0A
+    @SuppressWarnings(%22unchecked%22)%0A
     private void
@@ -3854,16 +3854,25 @@
 t(Action
+%3C?, ?, ?%3E
  action,
@@ -3901,32 +3901,35 @@
 , ActionListener
+%3C?%3E
  listener) %7B%0A   
@@ -4010,25 +4010,30 @@
 st, new 
-Transport
+ActionListener
 Response
@@ -4043,28 +4043,17 @@
 dler
-%3CTransportResponse%3E(
+(listener
 ) %7B%0A
@@ -4191,469 +4191,8 @@
  %7D%0A%0A
-            @Override%0A            @SuppressWarnings(%22unchecked%22)%0A            public void handleResponse(TransportResponse response) %7B%0A                listener.onResponse(response);%0A            %7D%0A%0A            @Override%0A            public void handleException(TransportException exp) %7B%0A                listener.onFailure(exp);%0A            %7D%0A%0A            @Override%0A            public String executor() %7B%0A                return ThreadPool.Names.SAME;%0A            %7D%0A
     
@@ -4296,16 +4296,19 @@
 Listener
+%3C?%3E
  listene

use ActionListenerResponseHandler