package idc.cupon.command;

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

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 IdcCuponDeleteCmd implements IdcCmd
{
	private IdcDAO dao;
	
	public IdcCuponDeleteCmd()
	{
		dao = new IdcDAO();
	}
	//쿠폰 지워주는 부분
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		
		//checkToken 값이 다르면 true반환.
		if(dao.checkToken(request))
		{
			request.setAttribute("reError", dao.reError);
			return;
		}
		else
		{
			//토큰이 같아서 등록성공이 될 경우 토큰을 삭제해 준다.
			request.getSession().removeAttribute("token");
		}
		
		//해당 쿠폰 선택
		int num = Integer.parseInt(request.getParameter("num"));
		//해당 쿠폰 지우기
		delCup(num);
	}
	private void delCup(int num)
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="DELETE FROM cupondb WHERE cupon_num=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setInt(1, num);
			pstmt.executeUpdate();
		}
		catch (Exception e) 
		{
			System.out.println("IdcCuponDeleteCmd 에서의 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("IdcCuponDeleteCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
}
