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 IdcUseCuponCmd implements IdcCmd
{
	private IdcDAO dao;
	
	public IdcUseCuponCmd()
	{
		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"));
		useCupon(num);
	}
	private void useCupon(int num)
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="UPDATE cupondb SET cupon_current=cupon_current-1, cupon_use=cupon_use+1 ";
			sql+="WHERE cupon_num=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setInt(1, num);
			pstmt.executeUpdate();
		}
		catch (Exception e) 
		{
			System.out.println("IdcUseCuponCmd  - useCupon 에서의 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("IdcUseCuponCmd - useCupon 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
}
