package io.korobi.mongotoelastic.processor;

import com.mongodb.client.MongoCursor;
import io.korobi.mongotoelastic.exception.ImportException;
import io.korobi.mongotoelastic.logging.InjectLogger;
import io.korobi.mongotoelastic.mongo.IChannelBlacklist;
import org.apache.logging.log4j.Logger;
import org.bson.Document;
import org.elasticsearch.action.bulk.BulkRequestBuilder;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentFactory;

import javax.inject.Inject;
import java.io.IOException;
import java.util.Date;
import java.util.Scanner;
import java.util.concurrent.atomic.AtomicInteger;

public class ChannelDocumentProcessor implements IDocumentProcessor {

    @InjectLogger
    private Logger logger;
    private final Client esClient;
    private final IChannelBlacklist blacklist;

    @Inject
    public ChannelDocumentProcessor(Client esClient, IChannelBlacklist blacklist) {
        this.esClient = esClient;
        this.blacklist = blacklist;
    }

    @Override
    public void run(MongoCursor<Document> documents, int bulkSize) {
        throw new UnsupportedOperationException("No support for multithreaded channel import");
    }

    @Override
    public void run(MongoCursor<Document> documents) {
        // We don't have enough channels to necessitate processing in a multithreaded manner
        while (documents.hasNext()) {
            Document doc = documents.next();
            String network = doc.getString("network");
            String channel = doc.getString("channel");
            logger.info("ORIGINAL: " + doc.toJson());
            if (this.blacklist.isBlacklisted(network, channel)) {
                logger.info(String.format("Skipping channel %s on network %s due to blacklist.", channel, network));
                continue;
            }

            try {
                XContentBuilder builder = buildDocument(doc);
                logger.info(builder.prettyPrint().string());
                logger.info("You *must* press a key");
                (new Scanner(System.in)).nextLine();
            } catch (IOException e) {
                logger.error(e);
            }
        }
    }

    private XContentBuilder buildDocument(Document doc) throws IOException {
        // The fun part about storing these two dates is that it means we
        // ideally need to reindex the channel object every time someone
        // joins/parts/quits.

        Date lastValidContentAt = doc.getDate("last_valid_content_at");
        Date lastActivity = doc.getDate("last_activity");
        logger.info(doc.get("topic"));
        return XContentFactory.jsonBuilder()
                .startObject()
                    .field("mongoId", doc.get("_id").toString())
                    .field("channel", doc.getString("channel"))
                    .field("network", doc.getString("network"))
                    .field("network", doc.getString("network"))
                    .field("last_valid_content_at", lastValidContentAt.getTime())
                    .field("last_activity", lastActivity.getTime())
                    .startObject("topic")
                        .field("actor_host", doc.getString("topic.actor_host")) // ??
                    .endObject()
                .endObject();
    }

}

@@ -1454,16 +1454,86 @@
  manner%0A
+        BulkRequestBuilder bulkRequest = this.esClient.prepareBulk();%0A
         
@@ -1558,24 +1558,24 @@
 asNext()) %7B%0A
-
             
@@ -1721,62 +1721,8 @@
 %22);%0A
-            logger.info(%22ORIGINAL: %22 + doc.toJson());%0A
     
@@ -2102,44 +2102,92 @@
     
-logger.info(%22You *must* press a key%22
+bulkRequest.add(this.esClient.prepareIndex(%22channels%22, %22channel%22).setSource(builder)
 );%0A 
@@ -2329,24 +2329,769 @@
 %7D%0A        %7D%0A
+        logger.info(%22Submitting BR for %7B%7D channels%22, bulkRequest.numberOfActions());%0A        processBulkRequest(bulkRequest);%0A    %7D%0A%0A    private void processBulkRequest(BulkRequestBuilder bulkRequest) %7B%0A        if (bulkRequest.numberOfActions() == 0) %7B%0A            return;%0A        %7D%0A%0A        BulkResponse bulkResponse = bulkRequest.execute().actionGet();%0A        if (bulkResponse.hasFailures()) %7B%0A            logger.error(%22Bulk response failure! (this is bad!) Message: %7B%7D%22, bulkResponse.getItems()%5B0%5D.getFailureMessage());%0A            throw new ImportException(bulkResponse.getItems()%5B0%5D.getFailureMessage());%0A        %7D else %7B%0A            logger.info(%22%7B%7D channels were processed by the bulk request.%22, bulkRequest.numberOfActions());%0A        %7D%0A
     %7D%0A%0A    p
@@ -3474,47 +3474,8 @@
 %22);%0A
-        logger.info(doc.get(%22topic%22));%0A
     
@@ -3743,72 +3743,8 @@
 %22))%0A
-                    .field(%22network%22, doc.getString(%22network%22))%0A
     
@@ -3987,41 +3987,353 @@
 .get
-String(%22topic.actor_host%22)) // ??
+(%22topic%22, Document.class).getString(%22actor_host%22))%0A                        .field(%22actor_nick%22, doc.get(%22topic%22, Document.class).getString(%22actor_nick%22))%0A                        .field(%22time%22, doc.get(%22topic%22, Document.class).getDate(%22time%22).getTime())%0A                        .field(%22value%22, doc.get(%22topic%22, Document.class).getString(%22value%22))
 %0A   

Tidy up channel importer