package jp.sf.amateras.mirage;

import static org.mockito.Mockito.*;

import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Collections;

import jp.sf.amateras.mirage.annotation.PrimaryKey;
import jp.sf.amateras.mirage.annotation.PrimaryKey.GenerationType;
import jp.sf.amateras.mirage.bean.BeanDesc;
import jp.sf.amateras.mirage.dialect.Dialect;
import jp.sf.amateras.mirage.naming.NameConverter;
import jp.sf.amateras.mirage.type.ValueType;
import junit.framework.TestCase;


public class DefaultResultEntityCreatorTest extends TestCase {
	
	DefaultResultEntityCreator ec = new DefaultResultEntityCreator();
	
	public void testDefaultResultEntityCreator() throws SQLException {
		ResultSet rs = mock(ResultSet.class);
		ResultSetMetaData meta = mock(ResultSetMetaData.class);
		BeanDesc beanDesc = mock(BeanDesc.class);
		Dialect dialect = mock(Dialect.class);
		NameConverter nc = mock(NameConverter.class);
		
		// Although UserInfo doesn't have public no-args constructor,
		// DefaultResultEntityCreator can create UserInfo instance
		UserInfo userInfo = ec.createEntity(UserInfo.class, rs, meta, 0,
				beanDesc, dialect, Collections.<ValueType<?>>emptyList(), nc);
		assertNotNull(userInfo);
		
		// If the entity class doesn't have no-args constructor,
		// EntityCreationFailedException is thrown.
		try {
			ec.createEntity(UserInfo2.class, rs, meta, 0,
					beanDesc, dialect, Collections.<ValueType<?>>emptyList(), nc);
			fail();
		} catch (EntityCreationFailedException e) {
			// success
		}
	}
	
	public static class UserInfo {
		
		@PrimaryKey(generationType=GenerationType.IDENTITY)
		private int userId;
		
		private String userName;
		
		public UserInfo(int userId, String userName) {
			this.userId = userId;
			this.userName = userName;
		}
		
		@SuppressWarnings("unused") // for reflective access
		private UserInfo() {
		}

		public int getUserId() {
			return userId;
		}

		public void setUserId(int userId) {
			this.userId = userId;
		}

		public String getUserName() {
			return userName;
		}

		public void setUserName(String userName) {
			this.userName = userName;
		}
		
		@Override
		public String toString() {
			return userId + " " + userName;
		}
	}

	
	public static class UserInfo2 {
		
		@PrimaryKey(generationType=GenerationType.IDENTITY)
		private int userId;
		
		private String userName;
		
		public UserInfo2(int userId, String userName) {
			this.userId = userId;
			this.userName = userName;
		}
		
		public int getUserId() {
			return userId;
		}

		public void setUserId(int userId) {
			this.userId = userId;
		}

		public String getUserName() {
			return userName;
		}

		public void setUserName(String userName) {
			this.userName = userName;
		}
		
		@Override
		public String toString() {
			return userId + " " + userName;
		}
	}
}
