package idc.deposit.command;

import idc.model.IdcCmd;
import idc.model.IdcDAO;

import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class IdcReSendBillPaperFormCmd implements IdcCmd
{
	IdcDAO dao = new IdcDAO();
	
	//보낸 메일 가져오기.
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		String content = getContent(Integer.parseInt(request.getParameter("num")));
		
		request.setAttribute("content", content);
	}

	private String getContent(int num)
	{
		String result = "";
		
		FileReader fr = null;
		BufferedReader br = null;
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT filepath FROM mailsave WHERE num=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setInt(1, num);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				String temp = null;
				fr = new FileReader(rs.getString("filepath"));
				br = new BufferedReader(fr);
				//sendmail.jsp에서 이전페이지로 돌아가기위해 해놓은 변수
				//이곳은 재발송페이지이기 때문에 재발송 페이지로 돌아가기위해 URL을 바꿔준다.
				while((temp = br.readLine()) != null)
				{
					result = result.concat(temp);
				}
				result = result.replaceAll("IdcDepositNonPaymentList", "IdcReSendMailList");
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcReSendBillPaperFormCmd 에서의 exception");
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(conn!=null) conn.close();
				if(pstmt!=null)pstmt.close();
				if(rs!=null)rs.close();
				if(br!=null)br.close();
				if(fr!=null)fr.close();
			}
			catch (SQLException e) 
			{
				System.out.println("IdcReSendBillPaperFormCmd 에서의 sqlexception");
				e.printStackTrace();
			}
			catch(Exception e)
			{
				System.out.println("IdcReSendBillPaperFormCmd 에서 fileclose의 exception");
				e.printStackTrace();
			}
		}
		return result;
	}
}
