package com.github.rnewson.couchdb.lucene;

import static java.util.concurrent.TimeUnit.SECONDS;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assume.assumeTrue;

import java.io.File;
import java.io.IOException;

import net.sf.json.JSONObject;

import org.apache.commons.io.FileUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

/**
 * This test class requires a running couchdb instance on localhost port 5984.
 * 
 * @author rnewson
 * 
 */
public class IntegrationTest {

    private final String base = "http://localhost:5984/";
    private final String dbname = "lucenetestdb";

    private Database db;

    @Before
    public void setup() throws IOException, InterruptedException {
        final File dir = new File("target/output");
        FileUtils.cleanDirectory(dir);
        System.setProperty("couchdb.lucene.dir", dir.getAbsolutePath());
        db = new Database(base);
        try {
            db.deleteDatabase(dbname);
            db.createDatabase(dbname);
        } catch (final IOException e) {
            assumeTrue(false);
        }
    }

    @After
    public void teardown() throws IOException {
        // db.deleteDatabase(dbname);
    }

    @Test
    public void index() throws IOException, InterruptedException {
        final String ddoc = "{\"fulltext\": {\"idx\": {\"index\":\"function(doc) {var ret=new Document(); ret.add(doc.content); return ret;}\"}}}";
        assertThat(db.saveDocument(dbname, "_design/lucene", ddoc), is(true));
        for (int i = 0; i < 50; i++) {
            assertThat(db.saveDocument(dbname, "doc-" + i, "{\"content\":\"hello\"}"), is(true));
        }
        SECONDS.sleep(5);

        final JSONObject indexState = db.getDoc(dbname, "_fti");
        assertThat(indexState.getInt("doc_count"), is(51));
    }

}

@@ -225,29 +225,8 @@
 e;%0A%0A
-import java.io.File;%0A
 impo
@@ -286,48 +286,8 @@
 t;%0A%0A
-import org.apache.commons.io.FileUtils;%0A
 impo
@@ -719,172 +719,8 @@
 n %7B%0A
-        final File dir = new File(%22target/output%22);%0A        FileUtils.cleanDirectory(dir);%0A        System.setProperty(%22couchdb.lucene.dir%22, dir.getAbsolutePath());%0A
     
@@ -998,11 +998,8 @@
     
- //
  db.
@@ -1476,24 +1476,25 @@
 ;%0A        %7D%0A
+%0A
         SECO
@@ -1503,17 +1503,17 @@
 S.sleep(
-5
+6
 );%0A%0A    
@@ -1632,16 +1632,165 @@
 is(51));
+%0A%0A        final JSONObject queryResult = db.getDoc(dbname, %22/_fti/lucene/idx?q=hello%22);%0A        assertThat(queryResult.getInt(%22total_rows%22), is(50));
 %0A    %7D%0A%0A

enhance integration test.