package eu.dnetlib.r2d2.mongodb;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.UnknownHostException;

import javax.annotation.Resource;

import me.prettyprint.cassandra.service.PoolExhaustedException;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.mongodb.Mongo;
import com.mongodb.MongoException;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/eu/dnetlib/r2d2/mongodb/applicationContext-r2d2-mongo.xml", "/eu/dnetlib/r2d2/mongodb/applicationContext-r2d2-mongo-test.xml"})
public class TestMongoFileStore {

	@Resource
	private MongoFileStore store = null;
	
	private String fileId = "fileId";

	@Test
	public void test() throws IllegalStateException, PoolExhaustedException, Exception {
		String testString = "This is the data of laaaaarge file that we are going to store to mongo db.";
		InputStream is = new ByteArrayInputStream(testString.getBytes());
		
		this.store.write(fileId, is);
		
		is.close();
		
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		
		this.store.read(fileId, baos);
		
		Assert.assertEquals(testString, new String(baos.toByteArray()));
		
		baos.close();
		
		store.delete(fileId);
	}
	
	@Test
	public void testLargeFile() throws IllegalStateException, PoolExhaustedException, Exception {
		File f = new File("/tmp/jetty-6.1.17.zip");
		
		if (f.exists()) {
			InputStream is = new FileInputStream(f);
			
			this.store.write(fileId, is);
			
			is.close();
			
			FileOutputStream fos = new FileOutputStream("/tmp/gridfs.out");
			
			store.read(fileId, fos);
			
			fos.close();
		}
	}
}