package idc.service.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 IdcDeffenceDeleteCmd implements IdcCmd
{
	private IdcDAO dao;
	
	public IdcDeffenceDeleteCmd()
	{
		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");
		}
			
		String doWhat = request.getParameter("doWhat");
		int num = Integer.parseInt(request.getParameter("num"));
		
		switch(doWhat)
		{
		case "def":
			delDef(num);
			break;
		case "sub":
			delSub(num);
			break;
		}
	}
	
	//deffence1add에서 삭제
	private void delSub(int num)
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="DELETE FROM deffence1add WHERE dadd_num=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setInt(1, num);
			pstmt.executeUpdate();
		}
		catch (Exception e) 
		{
			System.out.println("IdcDffenceDeleteCmd - delSub 에서의 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("IdcDffenceDeleteCmd - delSub 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
	
	//deffence1db에서 삭제
	private void delDef(int num)
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="DELETE FROM deffence1db WHERE deffence_num=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setInt(1, num);
			pstmt.executeUpdate();
		}
		catch (Exception e) 
		{
			System.out.println("IdcDffenceDeleteCmd - delDef 에서의 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("IdcDffenceDeleteCmd - delDef 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
			
}