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.DownloadLog;

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