package jp.sf.amateras.mirage.integration.spring;

import java.lang.reflect.Field;

import jp.sf.amateras.mirage.AbstractDatabaseTest;
import jp.sf.amateras.mirage.SqlManager;
import jp.sf.amateras.mirage.SqlManagerImpl;
import jp.sf.amateras.mirage.SqlManagerImplTest.Book;
import jp.sf.amateras.mirage.dialect.Dialect;
import jp.sf.amateras.mirage.dialect.HyperSQLDialect;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringConnectionProviderTest extends AbstractDatabaseTest {

	private static final String APPLICATION_CONTEXT =
		"jp/sf/amateras/mirage/integration/spring/applicationContext.xml";

	/**
	 * Tests dialect configuration.
	 */
	public void testSpringSpringConnectionProvider1() throws Exception {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(APPLICATION_CONTEXT);

		SqlManager sqlManager = (SqlManager) applicationContext.getBean("sqlManager");

		Field field = SqlManagerImpl.class.getDeclaredField("dialect");
		field.setAccessible(true);
		Dialect dialect = (Dialect) field.get(sqlManager);

		assertTrue(dialect instanceof HyperSQLDialect);
	}

	/**
	 * Tests SQL execusion (commit).
	 */
	public void testSpringSpringConnectionProvider2() throws Exception {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(APPLICATION_CONTEXT);

		SpringTestDao springTestDao = (SpringTestDao) applicationContext.getBean("springTestDao");

		Book book = new Book();
		book.bookName = "Mirage in Action";
		book.author = "Naoki Takezoe";
		book.price = 20;
		springTestDao.insert(book, false);

		assertEquals(1, springTestDao.getCount());
	}

	/**
	 * Tests SQL execusion (rollback).
	 */
	public void testSpringSpringConnectionProvider3() throws Exception {
		ApplicationContext applicationContext = new ClassPathXmlApplicationContext(APPLICATION_CONTEXT);

		SpringTestDao springTestDao = (SpringTestDao) applicationContext.getBean("springTestDao");

		Book book = new Book();
		book.bookName = "Mirage in Action";
		book.author = "Naoki Takezoe";
		book.price = 20;
		try {
			springTestDao.insert(book, true);
			fail();
		} catch(RuntimeException ex){
		}

		assertEquals(0, springTestDao.getCount());
	}

}
