package org.eclipse.hawk.greycat.tests;

import static org.junit.Assert.assertEquals;

import java.util.Collections;

import org.eclipse.hawk.backend.tests.TemporaryDatabaseTest;
import org.eclipse.hawk.backend.tests.factories.IGraphDatabaseFactory;
import org.eclipse.hawk.core.graph.IGraphTransaction;
import org.eclipse.hawk.core.graph.timeaware.ITimeAwareGraphDatabase;
import org.eclipse.hawk.core.graph.timeaware.ITimeAwareGraphNode;
import org.eclipse.hawk.greycat.lucene.GreycatLuceneIndexer.GreycatLuceneNodeIndex;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;

@RunWith(Parameterized.class)
public class GreycatLuceneTestSuite extends TemporaryDatabaseTest {

	@Parameters(name="{0}")
	public static Object[][] params() {
		return new Object[][] {
			{ new LevelDBGreycatDatabaseFactory() },
		};
	}

	private ITimeAwareGraphDatabase tadb;
	private ITimeAwareGraphNode n;

	public GreycatLuceneTestSuite(IGraphDatabaseFactory dbf) {
		super(dbf);
	}

	@Override
	@Before
	public void setup() throws Exception {
		super.setup();
		tadb = (ITimeAwareGraphDatabase)db;

		try (IGraphTransaction tx = tadb.beginTransaction()) {
			n = tadb.createNode(Collections.emptyMap(), "testnodes");
			tx.success();
		}
	}

	@Test
	public void addRemoveNode() throws Exception {
		GreycatLuceneNodeIndex idx = (GreycatLuceneNodeIndex) tadb.getOrCreateNodeIndex("test");
		
		try (IGraphTransaction tx = tadb.beginTransaction()) {
			idx.add(n, "x", 1);
			tx.success();
		}

		try (IGraphTransaction tx = tadb.beginTransaction()) {
			assertEquals(1, idx.query("x", 1).size());
			tx.success();
		}

		try (IGraphTransaction tx = tadb.beginTransaction()) {
			idx.remove(n);
			tx.success();
		}

		assertEquals(0, idx.countAll());
	}

	@Test
	public void addRemoveNodeValue() throws Exception {
		GreycatLuceneNodeIndex idx = (GreycatLuceneNodeIndex) tadb.getOrCreateNodeIndex("test");
		
		try (IGraphTransaction tx = tadb.beginTransaction()) {
			idx.add(n, "x", 1);
			tx.success();
		}

		try (IGraphTransaction tx = tadb.beginTransaction()) {
			assertEquals(1, idx.query("x", 1).size());
			tx.success();
		}

		try (IGraphTransaction tx = tadb.beginTransaction()) {
			idx.remove(n, "x", 1);
			tx.success();
		}
		
		assertEquals(0, idx.countAll());
	}

}
