package jp.yoyoyoyo.webformmanager.dao;

import java.sql.Connection;
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.LoginLog;

public class LoginLogDAO {
	// データ一覧を検索するSQL
	private static final String SELECT = "select * from LOGIN_LOG";
	
	private DataSource source;
	
	public LoginLogDAO(){
		source = DaoUtil.getSource();
	}
	
	public List<LoginLog> getLoginLog(String where) throws SQLException {
		List<LoginLog> list = new ArrayList<LoginLog>();
		
		String sql = SELECT + where + " order by LOGIN_DATE desc";;
		
		Connection conn = source.getConnection();
		ResultSet rs = null;
		
		// ステートメントを作成
	    Statement stmt = conn.createStatement(); 
	    try{
	    	rs = stmt.executeQuery(sql);
	    	
	    	while(rs.next()){
	    		list.add(getLoginLog(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 LoginLog getLoginLog(ResultSet rs) throws SQLException {
		LoginLog log = new LoginLog();
		
		log.setId(rs.getString("OPERATOR_ID"));
		log.setLoginSuccessful(rs.getInt("LOGIN_SUCCESSFUL"));
		log.setLoginDate(rs.getTimestamp("LOGIN_DATE"));
		log.setIpAddress(rs.getString("IP_ADDRESS"));
		log.setSessionId(rs.getString("SESSION_ID"));
		
		return log;
	}
}
