package jp.yoyoyoyo.webformmanager.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import jp.yoyoyoyo.webformmanager.model.MstUser;

public class MstUserDAO {
	// データ一覧を検索するSQL
	private static final String SELECT = "select * from MST_USER";
	
	private static final String SELECT_BY_ID = "select * from MST_USER where OPERATOR_ID = ?";
	
	private DataSource source;
	
	public MstUserDAO(){
		source = DaoUtil.getSource();
	}
	
	public MstUser getMstUserById(String id) throws SQLException {
		Connection conn = source.getConnection();
		ResultSet rs = null;
		
		// ステートメントを作成
	    PreparedStatement stmt = conn.prepareStatement(SELECT_BY_ID); 
	    
	    try{
	    	
	    	stmt.setString(1, id);
	    	rs = stmt.executeQuery();
	    	
	    	if(rs.next()){
	    		return getMstUser(rs);
	    	}
	    	
	    } catch (SQLException e){
	    	throw e;
	    } finally {
	    
	    	if(rs != null){
	    		rs.close();
	    	}
	    	
	    	if(stmt != null){
	    		stmt.close();
	    	}
	    	
	    	if(conn != null){
	    		conn.close();
	    	}
	    }
		
	    return null;
	}
	
	public List<MstUser> getMstUser(String where) throws SQLException {
		List<MstUser> list = new ArrayList<MstUser>();
		
		String sql = SELECT + where;
		
		Connection conn = source.getConnection();
		ResultSet rs = null;
		
		// ステートメントを作成
	    Statement stmt = conn.createStatement(); 
	    try{
	    	rs = stmt.executeQuery(sql);
	    	
	    	while(rs.next()){
	    		list.add(getMstUser(rs));
	    	}
	    	
	    } catch (SQLException e){
	    	throw e;
	    } finally {
	    
	    	if(rs != null){
	    		rs.close();
	    	}
	    	
	    	if(stmt != null){
	    		stmt.close();
	    	}
	    	
	    	if(conn != null){
	    		conn.close();
	    	}
	    }
		
	    return list;
	}
	
	private MstUser getMstUser(ResultSet rs) throws SQLException {
		MstUser user = new MstUser();
		
		user.setOperatorId(rs.getString("OPERATOR_ID"));
		user.setPassword(rs.getString("PASSWORD"));
		user.setOperatorName(rs.getString("OPERATOR_NAME"));
		user.setRole(rs.getString("ROLE"));
		user.setRoleText(rs.getString("ROLE_TEXT"));
		user.setLastPasswordChange(rs.getTimestamp("LAST_PASSWORD_CHANGE"));
		user.setInitialPassword(rs.getInt("INITIAL_PASSWORD"));
		user.setLockFlag(rs.getInt("LOCK_FLAG"));
		user.setFailedCount(rs.getInt("FAILED_COUNT"));
		user.setLastLoginDate(rs.getTimestamp("LAST_LOGIN_DATE"));
		user.setLastLoginDate2(rs.getTimestamp("LAST_LOGIN_DATE2"));
		user.setDateCreated(rs.getTimestamp("DATE_CREATED"));
		user.setDisabled(rs.getInt("DISABLED"));
		
		return user;
	}
	
}
