package idc.service.command;

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;

import utility.IdcSetIP;
import idc.model.*;

public class IdcDeleteALLItemCmd implements IdcCmd{
	
	IdcDAO dao = new IdcDAO();
	
	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[] vpn = null;
		String service_code = request.getParameter("service_code");
		String client_code = request.getParameter("client_code");
		String reason = request.getParameter("reason");
		
		String str = request.getParameter("service_line");
		String[] result;
		String service_line = "";
		if(str != null && str != ""){
			result = str.split(" ");
			service_line = result[0];
		}
		
		vpn = service_code.split("-");
		
		if(vpn[0].equals("VPN")){
			cancelSubService(service_code, reason);
			cancelVpn(service_code, reason);
			deleteService(service_code);
		}else{
			//일일 변동사항 업데이트
			updateChangeDB(client_code,  service_code, service_line);			
			request.setAttribute("client_code", client_code);
			setDeleteService(service_code, reason);
			cancelSubService(service_code, reason);
			deleteService(service_code, reason);
		}
	}
	
	//vpn 부가서비스로 지우기
	private void cancelVpn(String service_code, String reason)
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		
		try	
		{
			conn=dao.getConn();
			String sql="SELECT * FROM adddb WHERE service_code=? ";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, service_code);
			rs=pstmt.executeQuery();
			
			while(rs.next())
			{
				IdcDeleteServiceItemCmd.deleteItem(Integer.toString(rs.getInt("adddb_num")),"addDB", reason);
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcDeleteALLItemCmd - cancelIp 에서의 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("IdcDeleteALLItemCmd - cancelIp 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
//	vpn 부가서비스로 지웠으니 서비스에서 삭제하
	private void deleteService(String service_code)
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="DELETE FROM servicedb WHERE service_code=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, service_code);
			pstmt.executeUpdate();
		}
		catch (Exception e) 
		{
			System.out.println("IdcDeleteALLItemCmd - deleteService 에서의 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("IdcDeleteALLItemCmd - deleteService 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
	
	//서비스DB -> 서비스 deleteDB로 이전하기
	private void setDeleteService(String service_code, String reason)
	{
		IDCserviceListDTO dto = new IDCserviceListDTO();
		Connection conn=null;
		PreparedStatement pstmt=null, pstmt2=null, pstmt3=null, pstmt4=null, cpstmt=null;
		ResultSet rs=null, rs3=null;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT * FROM servicedb WHERE service_code=? ";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, service_code);
			rs=pstmt.executeQuery();
			if(rs.next())
			{
				dto.setService_status(rs.getString("service_status"));
				dto.setService_code(rs.getString("service_code"));
				dto.setClient_code(rs.getString("client_code"));
				dto.setService_line(rs.getString("service_line"));
				dto.setServer_code(rs.getString("server_code"));
				dto.setService_sw(rs.getString("service_sw"));
				dto.setService_os(rs.getString("service_os"));
				dto.setService_ip(rs.getString("service_ip"));
				dto.setService_request_date(rs.getDate("service_request_date"));
				dto.setService_payment_date(rs.getDate("service_payment_date"));
				dto.setService_open_date(rs.getDate("service_open_date"));
				dto.setService_amount(rs.getString("service_amount"));
				dto.setService_nonpayment(rs.getString("service_nonpayment"));
				dto.setService_note(rs.getString("service_note"));
				dto.setService_manager(rs.getString("service_manager"));
				dto.setService_case(rs.getString("service_case"));
				dto.setService_defence(rs.getString("service_defence"));
				dto.setService_admin(rs.getString("service_admin"));
				dto.setService_cost(rs.getString("service_cost"));
			}
			
//			delete서비스 보고 복구 할 수 있는 정보 copyservice에 등록
			sql="INSERT INTO copyservice (client_code, service_line, server_code, service_sw, service_os, service_ip, ";
			sql+="service_request_date, service_open_date, service_payment_date, amount_rack, amount_line, amount_cpu, ";
			sql+="service_defence, amount_long, amount_pre, amount_authority, amount_contact, service_deduction, amount_sub_discount) ";
			sql+="SELECT client_code, service_line, server_code, service_sw, service_os, service_ip, ";
			sql+="service_request_date, service_open_date, service_payment_date, amount_rack, amount_line, amount_cpu, ";
			sql+="service_defence, amount_long, amount_pre, amount_authority, amount_contact, service_deduction, amount_sub_discount ";
			sql+="FROM servicedb as s, amountdb as a ";
			sql+="WHERE s.service_code=?";
			cpstmt = conn.prepareStatement(sql);
			cpstmt.setString(1, service_code);
			cpstmt.executeUpdate();
			
			
			sql="SELECT * FROM serverdb WHERE server_code=?";
			pstmt3=conn.prepareStatement(sql);
			pstmt3.setString(1, dto.getServer_code());
			rs3=pstmt3.executeQuery();
			if(rs3.next())
			{
				dto.setServer_spec(rs3.getString("server_process")+" "+rs3.getString("server_spec")+" "+rs3.getString("server_cpuname"));
			}
			
			sql="INSERT INTO deleteservicedb (service_status, service_code, client_code, service_line, server_code, service_sw, service_os, ";
			sql+="service_ip, service_request_date, service_payment_date, service_open_date, service_amount, service_nonpayment, service_note, ";
			sql+="service_manager, service_case, service_defence, service_admin, service_cost, service_cancel_date , server_spec) ";
			sql+="values(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, curdate(), ?)";
			pstmt2=conn.prepareStatement(sql);
			pstmt2.setString(1, dto.getService_status());
			pstmt2.setString(2, dto.getService_code());
			pstmt2.setString(3, dto.getClient_code());
			pstmt2.setString(4, dto.getService_line());
			pstmt2.setString(5, dto.getServer_code());
			pstmt2.setString(6, dto.getService_sw());
			pstmt2.setString(7, dto.getService_os());
			pstmt2.setString(8, dto.getService_ip());
			pstmt2.setDate(9, dto.getService_request_date());
			pstmt2.setDate(10, dto.getService_payment_date());
			pstmt2.setDate(11, dto.getService_open_date());
			pstmt2.setString(12, dto.getService_amount());
			pstmt2.setString(13, dto.getService_nonpayment());
			pstmt2.setString(14, dto.getService_note() + "<br> 해지사유 : "+ reason);
			pstmt2.setString(15, dto.getService_manager());
			pstmt2.setString(16, dto.getService_case());
			pstmt2.setString(17, dto.getService_defence());
			pstmt2.setString(18, dto.getService_admin());
			pstmt2.setString(19, dto.getService_cost());
			pstmt2.setString(20, dto.getServer_spec());
			
			pstmt2.executeUpdate();
			
			System.out.println("실행안됨?->"+pstmt2);
			sql="DELETE FROM csdb WHERE service_code=?";
			pstmt4 = conn.prepareStatement(sql);
			pstmt4.setString(1, service_code);
			pstmt4.executeUpdate();
		}
		catch (Exception e) 
		{
			System.out.println("IdcDeleteALLItemCmd - setDeleteService 에서의 exception");
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(conn!=null) conn.close();
				if(rs!=null)rs.close();
				if(pstmt!=null)pstmt.close();
				if(pstmt2!=null)pstmt2.close();
				if(rs3!=null)rs3.close();
				if(pstmt3!=null)pstmt3.close();
				if(pstmt4!=null)pstmt4.close();
			}
			catch (SQLException e) 
			{
				System.out.println("IdcDeleteALLItemCmd - setDeleteService 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
//	묶여있는 부가서비스 하나하나 삭제(deleteSub)로 돌리기.
	private void cancelSubService(String service_code, String reason)
	{
		cancelIp(service_code, reason);
		cancelVpc(service_code, reason);
		cancelKcs(service_code, reason);
		cancelDefence(service_code, reason);
	
	}
	
	//방어서비스 삭제
	private void cancelDefence(String service_code, String reason)
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		
		try	
		{
			conn=dao.getConn();
			String sql="SELECT * FROM adddb WHERE service_code=? AND (adddb_case='defence')";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, service_code);
			rs=pstmt.executeQuery();
			
			while(rs.next())
			{
				IdcDeleteServiceItemCmd.deleteItem(Integer.toString(rs.getInt("adddb_num")),"adddb_num", reason);
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcDeleteALLItemCmd - cancelDefence 에서의 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("IdcDeleteALLItemCmd - cancelDefence 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}

	//	kcs지우기
	private void cancelKcs(String service_code, String reason)
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
	
		try	
		{
			conn=dao.getConn();
			String sql="SELECT * FROM kcsdb WHERE service_code=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, service_code);
			rs=pstmt.executeQuery();
			
			while(rs.next())
			{
				IdcDeleteServiceItemCmd.deleteItem(rs.getString("kcs_num"), "kcsDB", reason);
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcDeleteALLItemCmd - cancelKcs 에서의 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("IdcDeleteALLItemCmd - cancelKcs 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
//	VPC 지우기
	private void cancelVpc(String service_code, String reason)
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
	
		try	
		{
			conn=dao.getConn();
			String sql="SELECT * FROM vpcdb WHERE service_code=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, service_code);
			rs=pstmt.executeQuery();
			
			while(rs.next())
			{
				IdcDeleteServiceItemCmd.deleteItem(rs.getString("vpc_num"),"vpcDB", reason);
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcDeleteALLItemCmd - cancelVpc 에서의 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("IdcDeleteALLItemCmd - cancelVpc 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
//	ip 지우기
	private void cancelIp(String service_code, String reason)
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		
		try	
		{
			conn=dao.getConn();
			String sql="SELECT * FROM adddb WHERE service_code=? AND (adddb_case='ip')";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, service_code);
			rs=pstmt.executeQuery();
			
			while(rs.next())
			{
				IdcDeleteServiceItemCmd.deleteItem(Integer.toString(rs.getInt("adddb_num")),"addDB", reason);
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcDeleteALLItemCmd - cancelIp 에서의 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("IdcDeleteALLItemCmd - cancelIp 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
// service 지우기
	public void deleteService(String service_code, String reason){
		Connection conn = null;
		PreparedStatement[] pstmt = new PreparedStatement[10];
		ResultSet rs = null;
		String sql;
		String server_code = "", client_code="IDCJP", location="", total="total", line="";
		try 
		{
			conn = dao.getConn();
			
//			서버 현황에서 빼기
			if(service_code.substring(0,1).equals("s"))
			{
				sql = "SELECT c.client_code, server_location, service_line, Client_Reseller, service_ip, service_cs ";
				sql += "FROM clientdb as c, serverdb as s, servicedb as v ";
				sql += "WHERE c.Client_Code=v.client_code AND s.server_code=v.server_code AND v.service_code=?";
				
				pstmt[7] = conn.prepareStatement(sql);
				pstmt[7].setString(1, service_code);
				rs = pstmt[7].executeQuery();
				
				while(rs.next())
				{
//					cs, ip 되돌려놓기.
					IdcSetIP.SetIP("", "", 1, "", "", rs.getString("service_ip"),"x",null,reason);
//					IdcSetIP.SetIP("", "", 1, "", "", rs.getString("service_cs"),"x",null,reason);
					if(!rs.getString("client_reseller").equals("0"))
						client_code = rs.getString("c.client_code");
					location = getLocation(rs.getString("service_line"), rs.getString("server_location"));
					total = getLocation(total,rs.getString("server_location"));
					line=rs.getString("service_line");
					if(line.equals("soloLine"))
						break;
					if(line.equals("test"))
						sql="UPDATE havelist SET "+location+" = "+location+"-1, "+total+" = "+total+" -1, test_total=test_total-1 ";
					else
						sql="UPDATE havelist SET "+location+" = "+location+"-1, "+total+" = "+total+" -1, total_total=total_total-1 ";
					
					sql+="WHERE client_code=?";
					pstmt[8] = conn.prepareStatement(sql);
					pstmt[8].setString(1, client_code);
					
					System.out.println("실행안됨2?->"+pstmt[8]);
					pstmt[8].executeUpdate();
				}
			}
			
			sql = "SELECT server_code FROM serviceDB WHERE service_code=?";
			pstmt[0] = conn.prepareStatement(sql);
			pstmt[0].setString(1, service_code);
			rs = pstmt[0].executeQuery();
			
			if(rs.next())
				server_code = rs.getString("server_code");
			
			sql = "DELETE FROM serviceDB WHERE service_code=?";
			pstmt[1] = conn.prepareStatement(sql);
			pstmt[1].setString(1, service_code);			
			pstmt[1].executeUpdate();
			
			//서비스를 지울때 부가 서비스도 같이 지움			
			sql = "DELETE FROM addDB WHERE service_code=?";
			pstmt[2] = conn.prepareStatement(sql);
			pstmt[2].setString(1, service_code);
			pstmt[2].executeUpdate();
			
			//kcsDB제거
			sql = "DELETE FROM kcsDB WHERE service_code=?";
			pstmt[3] = conn.prepareStatement(sql);
			pstmt[3].setString(1, service_code);
			pstmt[3].executeUpdate();
			
			//1회성 리스트에서 제거
			sql = "DELETE FROM onetimeDB WHERE service_code=?";
			pstmt[4] = conn.prepareStatement(sql);
			pstmt[4].setString(1, service_code);
			pstmt[4].executeUpdate();
			
			//vpcDB에서 제거
			sql = "DELETE FROM vpcDB WHERE service_code=?";
			pstmt[5] = conn.prepareStatement(sql);
			pstmt[5].setString(1, service_code);
			pstmt[5].executeUpdate();
						
			//서비스 삭제시 장비 가용여부 변경			
			sql = "UPDATE serverDB SET server_use_status='y', server_before_user=server_now_user, server_now_user='' ";
			sql += " WHERE server_code=?";			
			pstmt[6] = conn.prepareStatement(sql);						
			pstmt[6].setString(1, server_code);
			pstmt[6].executeUpdate();
			
			//서비스 삭제시 amountdb 제거
			sql = "DELETE FROM amountdb WHERE service_code=?";
			pstmt[9] = conn.prepareStatement(sql);
			pstmt[9].setString(1, service_code);
			pstmt[9].executeUpdate();
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try 
			{	
				for(int i=0;i<pstmt.length;i++)
					if(pstmt[i] != null) pstmt[i].close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
//	위치로 치바 도쿄 붙이기 _c/_t 붙이기
	private String getLocation(String _case, String location)
	{
		String result="";
		if(location.equals("tokyo"))
			result=_case.concat("_t");
		else if(location.equals("chiba"))
			result=_case.concat("_c");
		return result;
	}

	//일일 변동사항
	private void updateChangeDB(String client_code, String service_code, String service_line){
		Connection conn = null;
		PreparedStatement pstmt = null,pstmt2=null, pstmt3=null, pstmt4=null;
		ResultSet rs = null,rs2=null,rs4=null;
		int num = 0;
		String sql;
		String server_location = "";		
		String location = "";
		String client_name = "";
		String amount_reseller = "0";
				
		
		try {
			conn = dao.getConn();
			
			//서비스 라인이 vpn이면
			if(service_line.equals("vpn")){
				return;
			}else if(service_line.equals("test")){
				
				//서버 코드 및 서버 위치 받기
				sql="SELECT s.server_location, s.server_code FROM serverDB s, serviceDB c  WHERE c.server_code=s.server_code AND c.service_code=?";
				pstmt4 =conn.prepareStatement(sql);
				pstmt4.setString(1, service_code);
				rs4=pstmt4.executeQuery();
				
				if(rs4.next()){
					server_location = rs4.getString("server_location");
				}
				
				//서버 위치 및 고객 명 받기
				sql = "SELECT s.server_location, c.client_name, c.client_reseller FROM serverdb s, clientDB c, serviceDB v ";
				sql += " WHERE c.client_code=? AND v.service_code=? AND v.server_code = s.server_code ";
				
				pstmt =conn.prepareStatement(sql);
				pstmt.setString(1, client_code);
				pstmt.setString(2, service_code);
				rs = pstmt.executeQuery();			
				
				if(rs.next()){
					server_location = rs.getString("server_location");
					client_name = rs.getString("client_name");
					amount_reseller = rs.getString("client_reseller");
				}
				
				if(server_location.equals("tokyo")){
					location = "endTest_t";
				}else{
					location = "endTest_c";
				}
				
				if(amount_reseller.equals("0")){
					client_name = "IDCJP";
				}
				
			}else{
				//서버 코드 및 서버 위치 받기
				sql="SELECT s.server_location, s.server_code FROM serverDB s, serviceDB c  WHERE c.server_code=s.server_code AND c.service_code=?";
				pstmt4 =conn.prepareStatement(sql);
				pstmt4.setString(1, service_code);
				rs4=pstmt4.executeQuery();
				if(rs4.next()){				
					server_location = rs4.getString("server_location");
				}
				
				//서버 위치 및 고객 명 받기
				sql = "SELECT s.server_location, c.client_name, c.client_reseller FROM serverdb s, clientDB c, serviceDB v ";
				sql += " WHERE c.client_code=? AND v.service_code=? AND v.server_code = s.server_code ";
				
				pstmt =conn.prepareStatement(sql);
				pstmt.setString(1, client_code);
				pstmt.setString(2, service_code);
				rs = pstmt.executeQuery();			
				
				if(rs.next()){
					server_location = rs.getString("server_location");
					client_name = rs.getString("client_name");
					amount_reseller = rs.getString("client_reseller");
				}
				
				if(server_location.equals("tokyo")){
					location = "del_t";
				}else{
					location = "del_c";
				}
				
				if(amount_reseller.equals("0")){
					client_name = "IDCJP";
				}
			}
											
			//changeDB 오늘날짜 변동 사항이 있는지 확인
			sql = "SELECT count(num) AS NUM FROM changeDB where change_date = curdate() and client_name=?";
			pstmt2 = conn.prepareStatement(sql);
			pstmt2.setString(1, client_name);
			rs2 = pstmt2.executeQuery();
			
			if(rs2.next()){
				num = rs2.getInt("num");
			}
			
			//기존에 changeDB가 없다면
			if(num == 0){
				sql = "INSERT INTO changeDB (client_name, "+location+", change_date) ";
				sql += " values(?, ?, curdate())";
				pstmt3 =conn.prepareStatement(sql);
				pstmt3.setString(1, client_name);
				pstmt3.setInt(2, 1);
				pstmt3.executeUpdate();
			}else{				
				sql = "UPDATE changeDB SET "+location+"="+location +"+1 WHERE change_date = curdate() AND client_name=? ";				
				pstmt3 =conn.prepareStatement(sql);
				pstmt3.setString(1, client_name);
				pstmt3.executeUpdate();
			}
							
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
				if(rs2 != null) rs2.close();
				if(pstmt2 != null) pstmt2.close();
				if(pstmt3 != null) pstmt3.close();
				if(rs4 != null) rs4.close();
				if(pstmt4 != null) pstmt4.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}