
package org.canedata.provider.mongodb.test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.text.SimpleDateFormat;
import java.util.Date;

import org.bson.types.ObjectId;
import org.canedata.entity.Entity;
import org.canedata.exception.EntityNotFoundException;
import org.canedata.field.Fields;
import org.junit.Test;

/**
 * 
 * @author Sun Yat-ton
 * @version 1.00.000 2011-8-17
 */
public class TestRestore extends AbilityProvider {
	@Test
	public void strId(){
		Entity e = factory.get("user");
		assertNotNull(e);
		
		Fields f = e.restore("id:test:1");
		assertNotNull(f);
	}
	
	
	@Test
	public void allFields() {
		Entity e = factory.get("user");
		assertNotNull(e);

		Fields f = e.put("name", "cane").put("vendor", "cane team").create();
		assertNotNull(f);
		assertNotNull(f.get("_id"));

		Fields rlt = e.restore((ObjectId)f.get("_id"));

		assertEquals(f.get("_id"), rlt.get("_id"));
		assertEquals(rlt.getString("name"), "cane");
		assertEquals(rlt.getString("vendor"), "cane team");
		
		e.close();
	}

	@Test
	public void proj() {
		Entity e = factory.get("user");
		assertNotNull(e);

		Fields f = e.put("name", "cane").put("vendor", "cane team").create();
		assertNotNull(f);
		assertNotNull(f.get("_id"));

		Fields rlt = e.projection("name").restore((ObjectId)f.get("_id"));

		assertEquals(f.get("_id"), rlt.get("_id"));
		assertEquals(rlt.getString("name"), "cane");
		assertNull(rlt.getString("vendor"));
		
		
		f = e.restore("id:test:1");
		assertEquals(f.getFieldNames().length, 4);
		
		Fields f2 = e.projection("age").restore("id:test:1");
		assertEquals(f2.getFieldNames().length, 2);
		
		
		e.close();
	}
	
	@Test
	public void date(){
		Entity e = factory.get("user");
		assertNotNull(e);
		
		Date d = new Date();
		
		Fields r = e.put("date", d).create();
		Fields f = e.restore((ObjectId)r.get("_id"));
		assertNotNull(f);
		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
		assertTrue(d.equals(f.getDate("date")));
	}
	
	@Test
	public void notExist(){
		Entity e = factory.get("user");
		assertNotNull(e);
		
		try{
			e.relate("--xxxdd--bbccee--jk//--");
		}catch(EntityNotFoundException enfe){
			assertNotNull(enfe);
		}
		
		e.close();
	}
}
