package jp.yoyoyoyo.webformmanager.dao;

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

import javax.sql.DataSource;


import jp.yoyoyoyo.webformmanager.model.StatusHistory;

public class StatusHistoryDAO {
	private static final String SELECT_BY_ID = "select * from STATUS_HISTORY where SEQ_ID = ?";
	
	private DataSource source;
	
	public StatusHistoryDAO(){
		source = DaoUtil.getSource();
	}
	
	public List<StatusHistory> getStatusHistory(int id) throws SQLException {
		List<StatusHistory> list = new ArrayList<StatusHistory>();
		
		Connection conn = source.getConnection();
		ResultSet rs = null;
		
		// ステートメントを作成
		PreparedStatement stmt = conn.prepareStatement(SELECT_BY_ID); 
	    try{
	    	stmt.setInt(1, id);
	    	rs = stmt.executeQuery();
	    	
	    	while(rs.next()){
	    		list.add(getStatusHistory(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 StatusHistory getStatusHistory(ResultSet rs) throws SQLException {
		StatusHistory status = new StatusHistory();
		
		status.setId(rs.getInt("SEQ_ID"));
		status.setOldStatus(rs.getInt("OLD_STATUS"));
		status.setOldStatusText(rs.getString("OLD_STATUS_TEXT"));
		status.setNewStatus(rs.getInt("NEW_STATUS"));
		status.setNewStatusText(rs.getString("NEW_STATUS_TEXT"));
		status.setChangeComment(rs.getString("CHANGE_COMMENT"));
		status.setCreateDate(rs.getTimestamp("CREATE_DATE"));
		status.setOperatorId(rs.getString("OPERATOR_ID"));
		
		return status;
	}
}
