package egovframework;

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

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

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

public class DepartmentTest {
	
	protected EntityManagerFactory emf;	
	protected EntityManager em;	

    @Test
	public void testDepartment() throws Exception {

    	String modifyName = "Marketing Department";
    	String deptId = "DEPT-0001";
		Department department = makeDepartment(deptId);
		
		// Entity Manager 생성
		emf = Persistence.createEntityManagerFactory("PersistUnit");
		em = emf.createEntityManager();	
		
		// 입 력
		em.getTransaction().begin();
		em.persist(department);
		em.getTransaction().commit();	
		
		em.getTransaction().begin();
		Department departmentAfterInsert = em.find(Department.class, deptId );
		// 입력 확 인
		assertEquals("Department Name Compare!",department.getDeptName(),departmentAfterInsert.getDeptName());

		// 수 정
		departmentAfterInsert.setDeptName(modifyName);
		em.merge(departmentAfterInsert);
		em.getTransaction().commit();	
        
		em.getTransaction().begin();
		Department departmentAfterUpdate = em.find(Department.class, deptId );
		// 수 정 확 인
		assertEquals("Department Modify Name Compare!",modifyName,departmentAfterUpdate.getDeptName());
		
		// 삭 제
		em.remove(departmentAfterUpdate);
		em.getTransaction().commit();	

		// 삭 제 확 인
		Department departmentAfterDelete = em.find(Department.class, deptId );
		assertNull("Department is Deleted!",departmentAfterDelete);

		em.close();
		
	}
    
    private Department makeDepartment(String deptId) throws Exception {

		Department department = new Department();

		department.setDeptId(deptId);
		department.setDeptName("Sales Department");
		
		DateFormat df = new SimpleDateFormat ("yyyy-MM-dd");
		Date createDate = df.parse("2008-01-01");
		
		department.setCreateDate(createDate);
		department.setEmpCount(new BigDecimal(30));
		
		return department;
		
    }
	
}
