package fr.iri.thd.sonyengine.test;

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

import javax.ws.rs.core.MediaType;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.representation.Form;

import fr.iri.thd.sonyengine.core.DataAccessor;
import fr.iri.thd.sonyengine.core.DbEnv;

/*
 * 
 * import java.io.File;

import core.Tag;

/**
 * A class to test ThdEngine
 *
 * @author pachet
 *
public class ThdEngineTest {

 public static void main(String[] args) {
 testSimpleExampleManual();
//   testSimpleExampleFile();
 // testUniversCineFile();
 }

 /**
 * Tests the engine with a small set of movies and tags, entered
"manually", one by one
 private static void testSimpleExampleManual() {
 ThdEngine engine = ThdEngine.getEngine();
 engine.createMovieFragment("ref1");
 engine.createMovieFragment("ref2");
 engine.createMovieFragment("ref3");
 engine.createMovieFragment("ref4");
 engine.createMovieFragment("ref5");
 engine.createMovieFragment("ref6");
 engine.createMovieFragment("ref7");

 engine.addTag("crayon", "ref1");
 engine.addTag("carte", "ref1");
 engine.addTag("bateau", "ref1");
 engine.addTag("voiture", "ref1");
 engine.addTag("car", "ref1");

 engine.addTag("enfant", "ref2");
 engine.addTag("famille", "ref2");
 engine.addTag("violon", "ref2");
 engine.addTag("maison", "ref2");
 engine.addTag("hopital", "ref2");

 engine.addTag("enfant", "ref3");
 engine.addTag("famille", "ref3");
 engine.addTag("violon", "ref3");
 engine.addTag("maison", "ref3");
 engine.addTag("ordinateur", "ref3");
 engine.addTag("fenetre", "ref3");
 engine.addTag("voiture", "ref3");
 engine.addTag("guitare", "ref3");
 engine.addTag("carte", "ref3");

 engine.addTag("enfant", "ref4");
 engine.addTag("famille", "ref4");
 engine.addTag("violon", "ref4");
 engine.addTag("bateau", "ref4");
 engine.addTag("ordinateur", "ref4");
 engine.addTag("fenetre", "ref4");
 engine.addTag("stylo", "ref4");
 engine.addTag("perroquet", "ref4");
 engine.addTag("crayon", "ref4");
 engine.addTag("tele", "ref4");
 engine.addTag("bateau", "ref4");

 engine.addTag("ordinateur", "ref5");
 engine.addTag("crayon", "ref5");
 engine.addTag("fenetre", "ref5");
 engine.addTag("hopital", "ref5");
 engine.addTag("carte", "ref5");
 engine.addTag("tele", "ref5");
 engine.addTag("stylo", "ref5");
 engine.addTag("perroquet", "ref5");
 engine.addTag("bateau", "ref5");
 engine.addTag("guitare", "ref5");

 engine.addTag("maison", "ref6");
 engine.addTag("perroquet", "ref6");
 engine.addTag("stylo", "ref6");
 engine.addTag("guitare", "ref6");
 engine.addTag("hopital", "ref6");
 engine.addTag("tele", "ref6");
 engine.addTag("car", "ref6");
 engine.addTag("voiture", "ref6");
 engine.addTag("fenetre", "ref6");

 engine.addTag("car", "ref7");
 engine.addTag("voiture", "ref7");

 engine.reTrain();
 engine.showAllTagValues();

 //Neighbor neighbor = engine.findMore("ref1", "enfant", .05f, true);

 while (neighbor != null) {
  System.out.println(neighbor.getMovieRef() + " distance: "
    + neighbor.getDistance());
  neighbor = engine.findMore(neighbor.getMovieRef(), "enfant", .05f,
    true);
 }
 System.out.println("cannot find any better");
 }

 /**
 * Tests the engine with a xcl file containing references of movies and
 * their tags. esult should be the same than testSimpleExampleManual()
 public static void testSimpleExampleFile() {
 ThdEngine engine = ThdEngine.getEngine();
 engine.loadFromTextFile(new File("./Sessions/Essai.csv"));
 System.out.println("number of movies read: "
   + engine.getAllMovieFragments().size());

 engine.reTrain();
 engine.showAllTagValues();

 Neighbor neighbor = engine.findMore("ref1", "enfant", .05f, true);

 while (neighbor != null) {
  System.out.println(neighbor.getMovieRef() + " distance: "
    + neighbor.getDistance());
  neighbor = engine.findMore(neighbor.getMovieRef(), "enfant", .05f,
    true);
 }
 System.out.println("cannot find any better");
 }

 /**
 * Tests the engine with a xcl file containing references of movies and
 * their tags
 public static void testUniversCineFile() {
 ThdEngine engine = ThdEngine.getEngine();
 engine.loadFromTextFile(new File("./Sessions/MovieFrame2.csv"));
 System.out.println("number of movies read: "
   + engine.getAllMovieFragments().size());
 ThdMovieFragment sobibor = engine
   .movieFragmentNamed("Sobibor, 14 octobre 1943, 16 heures");
 engine.reTrain();

 Tag T_enfant = engine.tagNamed("Enfant");
 System.out.println(sobibor);
 System.out.println(T_enfant);

 engine.tagNamed("Enfant").valueFor(sobibor);

 Neighbor neighbor = engine.findMore(sobibor.getName(), "Enfant", .05f,
   true);

 while (neighbor != null) {
  System.out.println(neighbor.getMovieRef() + " distance: "
    + neighbor.getDistance());
  neighbor = engine.findMore(neighbor.getMovieRef(), "Enfant", .05f,
    true);
 }
 System.out.println("cannot find any better");
 }

}

 * 
 * 
 * 
 * 
 * 
 */


public class TestEngineResource {

	public static final String BASE_URL = "http://localhost:9080/sonyengine/";
	public static final String DATABASE_PATH = "/Users/ymh/dev/tmp/db";

	private DbEnv dbenv = null;
	private File databasePathFile = null;
	private String baseurl = null;
			
	@Before
	public void setup()
	{
		String databasepath = System.getProperty("database_path");
		if(databasepath == null)
			databasepath = DATABASE_PATH;
		databasePathFile = new File(databasepath);
		
		this.baseurl = System.getProperty("baseurl");
		if(this.baseurl == null)
			this.baseurl = BASE_URL;
	}
	
	@After
	public void teardown() {
	
		if(dbenv != null)
			dbenv.close();
	}
	

	
	
	
	@Test
	public void testCreateSequenceList() {

		List<String> movieIds = new ArrayList<String>();
		
		for(int i=0; i< 10; i++) {
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			movieIds.add("movie" + System.currentTimeMillis());
		}
				
		String xml = "<segments>";
		for(String sequenceId: movieIds) {
			xml += String.format("<segment id=\"%s\"/>", sequenceId);
		}
		xml += "</segments>";
		
		Client c = Client.create();
		WebResource res = c.resource(this.baseurl).path("segment").path("createall");
		Form form = new Form();
		form.add("xml", xml);
		String response = res.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_XML_TYPE).post(String.class, form);

		Assert.assertNotNull(response);

		dbenv = new DbEnv();
		dbenv.setup(databasePathFile, true, true);

		DataAccessor da = new DataAccessor(this.dbenv.getEntityStore());
		
		for(String sequenceId: movieIds) {		
			Assert.assertTrue(da.movieFragmentById.contains(sequenceId));
		}
		
	}
	
	
	@Test
	public void testReset() {
		Client c = Client.create();
		WebResource res = c.resource(this.baseurl);
		String response = res.path("engine").path("reset").accept(MediaType.TEXT_PLAIN).post(String.class);
		
		Assert.assertEquals(response, "ok");
		
		dbenv = new DbEnv();
		dbenv.setup(databasePathFile, true, true);

		DataAccessor da = new DataAccessor(this.dbenv.getEntityStore());

		Assert.assertEquals(0, da.movieFragmentById.count());
		Assert.assertEquals(0, da.tagById.count());
		Assert.assertEquals(0, da.tagByName.count());
		Assert.assertEquals(0, da.tagBySegment.count());		
		
	}
	
	
	@Test
	public void testClearTagsForm() {
		
		String movieName = "movie" + System.currentTimeMillis();
		
		List<String> tagNames = new ArrayList<String>();
		
		for(int i=0; i< 10; i++) {
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			tagNames.add("tag" + System.currentTimeMillis());
		}
		
		Client c = Client.create();
		WebResource res = c.resource(this.baseurl + "segment/create/" + movieName);
		String response = res.accept(MediaType.APPLICATION_XML_TYPE).post(String.class);
				
		Assert.assertNotNull(response);
		
		String xml = "<tags>";
		for(String tagName: tagNames) {
			xml += String.format("<tag name=\"%s\" segment=\"%s\"/>", tagName, movieName);
		}
		xml += "</tags>";
		
		res = c.resource(this.baseurl).path("tag").path("add");
		Form form = new Form();
		form.add("xml", xml);
		response = res.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_XML_TYPE).post(String.class, form);

		Assert.assertNotNull(response);

		form = new Form();
		form.add("id", movieName);
		
		res = c.resource(this.baseurl).path("segment").path("cleartags");
		response = res.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.TEXT_PLAIN).post(String.class,form);
		
		Assert.assertEquals("ok", response);

		
		dbenv = new DbEnv();
		dbenv.setup(databasePathFile, true, true);

		DataAccessor da = new DataAccessor(this.dbenv.getEntityStore());
		
		
		da = new DataAccessor(this.dbenv.getEntityStore());
		
		Assert.assertFalse(da.tagBySegment.contains(movieName));
		
		
	}

	@Test
	public void testClearTagsPath() {
		
		String movieName = "movie" + System.currentTimeMillis();
		
		List<String> tagNames = new ArrayList<String>();
		
		for(int i=0; i< 10; i++) {
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			tagNames.add("tag" + System.currentTimeMillis());
		}
		
		Client c = Client.create();
		WebResource res = c.resource(this.baseurl + "segment/create/" + movieName);
		String response = res.accept(MediaType.APPLICATION_XML_TYPE).post(String.class);
				
		Assert.assertNotNull(response);
		
		String xml = "<tags>";
		for(String tagName: tagNames) {
			xml += String.format("<tag name=\"%s\" segment=\"%s\"/>", tagName, movieName);
		}
		xml += "</tags>";
		
		res = c.resource(this.baseurl).path("tag").path("add");
		Form form = new Form();
		form.add("xml", xml);
		response = res.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_XML_TYPE).post(String.class, form);

		Assert.assertNotNull(response);
				
		res = c.resource(this.baseurl).path("segment").path("cleartags").path(movieName);
		response = res.type(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.TEXT_PLAIN).post(String.class);
		
		Assert.assertEquals("ok", response);

		dbenv = new DbEnv();
		dbenv.setup(databasePathFile, true, true);

		DataAccessor da = new DataAccessor(this.dbenv.getEntityStore());
				
		Assert.assertFalse(da.tagBySegment.contains(movieName));
		
	}

	
}
