package idc.deposit.command;

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

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

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

public class IdcDepositModifyCmd implements IdcCmd
{
	private IdcDAO dao;
	
	public IdcDepositModifyCmd()
	{
		dao = new IdcDAO();
	}
	
	//입금 수정창.
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		int num = Integer.parseInt(request.getParameter("num"));
		String deposit_date = request.getParameter("deposit_date");
		//String deposit_amount = request.getParameter("deposit_amount");
		String deposit_bank = request.getParameter("deposit_bank");
		String deposit_name = request.getParameter("deposit_name");
		String deposit_note = request.getParameter("deposit_note");
		String amount2 = request.getParameter("deposit_amount");
		String deposit_amount = amount2.replaceAll("\\,","");
		
		
		modify(num, deposit_date, deposit_amount, deposit_bank, deposit_name, deposit_note);
	}
	
	//수정
	private void modify(int num, String deposit_date, String deposit_amount, String deposit_bank, String deposit_name, String deposit_note)
	{
		Connection conn=null;
		PreparedStatement pstmt=null, pstmt2=null, pstmt3=null;
		ResultSet rs=null;
		int oldAmount = 0;
		String client_code = "";
		try	
		{
			conn=dao.getConn();
			String sql="SELECT deposit_amount, client_code FROM depositdb WHERE deposit_num=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setInt(1, num);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				oldAmount = rs.getInt("deposit_amount");
				client_code = rs.getString("client_code");
			}
			
		sql="UPDATE depositdb SET deposit_date=?, deposit_amount=?, deposit_bank=?, deposit_name=?, deposit_note=? WHERE deposit_num=?";
			pstmt2=conn.prepareStatement(sql);
			pstmt2.setDate(1, Date.valueOf(deposit_date));
			pstmt2.setInt(2, Integer.parseInt(deposit_amount));
			pstmt2.setString(3, deposit_bank);
			pstmt2.setString(4, deposit_name);
			pstmt2.setString(5, deposit_note);
			pstmt2.setInt(6, num);
			pstmt2.executeUpdate();
			
			sql="UPDATE clientdb SET client_money=client_money-?+? WHERE client_code=?";
			pstmt3=conn.prepareStatement(sql);
			pstmt3.setInt(1, oldAmount);
			pstmt3.setInt(2, Integer.parseInt(deposit_amount));
			pstmt3.setString(3, client_code);
			
			pstmt3.executeUpdate();
			
		}
		catch (Exception e) 
		{
			System.out.println("IdcDepositModifyCmd 에서의 exception");
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(conn!=null) conn.close();
				if(rs!=null)rs.close();
				if(pstmt!=null)pstmt.close();
				if(pstmt2!=null)pstmt2.close();
				if(pstmt3!=null)pstmt3.close();
			}
			catch (SQLException e) 
			{
				System.out.println("IdcDepositModifyCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
}
