/**
 * 
 */
package org.apache.solr.client.solrj.embedded;

import static org.junit.Assert.assertEquals;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.junit.*;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.CommonsHttpSolrServer;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrInputDocument;

/**
 * @author wjohnson
 * 
 */
public class TestJettyLargeVolume {

  SolrServer gserver = null;
  int numdocs = 1000 * 50;
  int threadCount = 5;
  String solrURL = "http://localhost:8983/solr";
  
  @Test
  public void testExampleConfig() throws Exception {
    gserver = new CommonsHttpSolrServer(solrURL);
    DocThread[] threads = new DocThread[threadCount];
    for (int i=0; i<threadCount; i++) {
      threads[i] = new DocThread();
      threads[i].setName("DocThread-" + i);
      threads[i].start();
      System.out.println("Started thread: " + i);
    }
    for (int i=0; i<threadCount; i++) {
      threads[i].join();
    }
    
    query(threadCount * numdocs);
    System.out.println("done");
  }

  private void query(int count) throws SolrServerException, IOException {
    SolrQuery query = new SolrQuery("*:*");
    QueryResponse response = gserver.query(query);
    Assert.assertEquals(0, response.getStatus());
    Assert.assertEquals(count, response.getResults().getNumFound());
  }

  public class DocThread extends Thread {
    
    SolrServer tserver = null;
    
    public void run() {
      try {
        tserver = new CommonsHttpSolrServer(solrURL);
        UpdateResponse resp = null;
        List<SolrInputDocument> docs = new ArrayList<SolrInputDocument>();
        for (int i = 0; i < numdocs; i++) {
          if (i > 0 && i % 200 == 0) {
            resp = tserver.add(docs);
            assertEquals(0, resp.getStatus());
            docs = new ArrayList<SolrInputDocument>();
          }
          if (i > 0 && i % 5000 == 0) {
            System.out.println(getName() + " - Committing " + i);
            resp = tserver.commit();
            assertEquals(0, resp.getStatus());
          }
          SolrInputDocument doc = new SolrInputDocument();
          doc.addField("id", String.valueOf(i));
          doc.addField("cat", "foocat");
          docs.add(doc);
        }
        resp = tserver.add(docs);
        assertEquals(0, resp.getStatus());
        resp = tserver.commit();
        assertEquals(0, resp.getStatus());
        resp = tserver.optimize();
        assertEquals(0, resp.getStatus());

      } catch (Exception e) {
        e.printStackTrace();
        Assert.fail(getName() + "---" + e.getMessage());
        System.exit(-1);
      }
    }
  }

}
