package idc.cupon.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 IdcCuponModifyFormCmd implements IdcCmd
{
	private IdcDAO dao;
	
	public IdcCuponModifyFormCmd()
	{
		dao = new IdcDAO();
	}
	
	//쿠폰 수정하기
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		modifyCup(request);
	}
	private void modifyCup(HttpServletRequest request)
	{
		int num = Integer.parseInt(request.getParameter("num"));
		Date cupon_request_date = Date.valueOf(request.getParameter("cupon_request_date"));
		int cupon_current = Integer.parseInt(request.getParameter("cupon_current"));
		int cupon_use = Integer.parseInt(request.getParameter("cupon_use"));
		int cupon_result = Integer.parseInt(request.getParameter("cupon_result"));
		String server_upgrade = request.getParameter("server_upgrade");
		Date cupon_end_date = Date.valueOf(request.getParameter("cupon_end_date"));
		String cupon_note = request.getParameter("cupon_note");
		
		//쿠폰 현재수량이 남은수량보다 많을경우
		//현재수량 = 남은수량 으로해준다.
		if(cupon_result < cupon_current)
			cupon_current=cupon_result;
		
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="UPDATE cupondb SET cupon_request_date=?, cupon_current=?, cupon_use=?, cupon_result=?, server_upgrade=?, cupon_end_date=?, cupon_note=? ";
			sql+="WHERE cupon_num=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setDate(1, cupon_request_date);
			pstmt.setInt(2, cupon_current);
			pstmt.setInt(3, cupon_use);
			pstmt.setInt(4, cupon_result);
			pstmt.setString(5, server_upgrade);
			pstmt.setDate(6, cupon_end_date);
			pstmt.setString(7, cupon_note);
			pstmt.setInt(8, num);
			pstmt.executeUpdate();
		}
		catch (Exception e) 
		{
			System.out.println("IdcCuponModifyFormCmd 에서의 exception");
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(conn!=null) conn.close();
				if(pstmt!=null)pstmt.close();
				if(rs!=null)rs.close();
			}
			catch (SQLException e) 
			{
				System.out.println("IdcCuponModifyFormCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
	
}
