package idc.service.command;

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

import idc.model.*;
import java.sql.*;

public class IdcDeleteServiceHandle implements IdcCmd{

	IdcDAO dao = new IdcDAO();
	
	public void execute(HttpServletRequest request, HttpServletResponse response) {
		
		String service_code = request.getParameter("service_code");
		String client_code = request.getParameter("client_code");
		String server_code = request.getParameter("server_code");
		deleteService(service_code, server_code);
		
		request.setAttribute("service_code", service_code);
		request.setAttribute("client_code", client_code);
	}
	
	//서비스 지우기
	public void deleteService(String service_code, String server_code){
		Connection conn = null;
		PreparedStatement pstmt = null, pstmt1 = null, pstmt2 = null, pstmt3 = null, pstmt4 = null, pstmt5 = null;
		String sql;
		
		try {
			conn = dao.getConn();			
			
			sql = "DELETE FROM serviceDB WHERE service_code=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, service_code);			
			pstmt.executeUpdate();
			
			//서비스를 지울때 부가 서비스도 같이 지움			
			sql = "DELETE FROM addDB WHERE service_code=?";
			pstmt1 = conn.prepareStatement(sql);
			pstmt1.setString(1, service_code);
			pstmt1.executeUpdate();
			
			//kcsDB제거
			sql = "DELETE FROM kcsDB WHERE service_code=?";
			pstmt2 = conn.prepareStatement(sql);
			pstmt2.setString(1, service_code);
			pstmt2.executeUpdate();
			
			//1회성 리스트에서 제거
			sql = "DELETE FROM onetimeDB WHERE service_code=?";
			pstmt3 = conn.prepareStatement(sql);
			pstmt3.setString(1, service_code);
			pstmt3.executeUpdate();
			
			//vpcDB에서 제거
			sql = "DELETE FROM vpcDB WHERE service_code=?";
			pstmt4 = conn.prepareStatement(sql);
			pstmt4.setString(1, service_code);
			pstmt4.executeUpdate();
			
			//서비스 삭제시 장비 가용여부 변경			
			sql = "UPDATE serverDB SET server_fomat_date=curdate(), server_before_user=server_now_user, server_now_user='' ";
			sql += " WHERE server_code=?";			
			pstmt5 = conn.prepareStatement(sql);						
			pstmt5.setString(1, server_code);
			pstmt5.executeUpdate();
												
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(pstmt != null) pstmt.close();
				if(pstmt1 != null) pstmt1.close();
				if(pstmt2 != null) pstmt2.close();
				if(pstmt3 != null) pstmt3.close();
				if(pstmt4 != null) pstmt4.close();
				if(pstmt5 != null) pstmt5.close();				
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

}