package idc.service.command;

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

import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.Date;
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 utility.IdcUpdateServiceAmount;

public class IdcDeleteServiceItemCmd implements IdcCmd{
	
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		IdcDAO dao = new IdcDAO();
		//checkToken 값이 다르면 true반환.
		if(dao.checkToken(request))
		{
			request.setAttribute("reError", dao.reError);
			return;
		}
		else
		{
			//토큰이 같아서 등록성공이 될 경우 토큰을 삭제해 준다.
			request.getSession().removeAttribute("token");
		}
		
		String service_code = request.getParameter("service_code");
		String client_code = request.getParameter("client_code");
						
		request.setAttribute("service_code", service_code);
		request.setAttribute("client_code", client_code);
		
		String content_code = request.getParameter("content_code");
		String content_db = request.getParameter("content_db");		
		String reason = request.getParameter("reason");

		deleteItem(content_code, content_db, reason);
		
	}
	
	//항목 삭제
	public static void deleteItem(String content_code, String content_db, String reason)
	{
		IdcDAO dao = new IdcDAO();
		//try
		//{
		//	reason = new String(reason.getBytes("8859_1"),"UTF-8");
		//}
		//catch (UnsupportedEncodingException e1)
		//{
		//	e1.printStackTrace();
		//}
		String sql;
		String item = "";
		switch(content_db)
		{		
		case "deffence1DB":			
			item = "deffence_num";
			break;
		case "deffence1add":
			item = "dadd_num";
			break;
		case "addDB":
			item = "addDB_num";
			break;
		case "vpcDB":
			item = "vpc_num";		
			break;
		case "kcsDB":
			item = "kcs_num";
			break;
		}

		Connection conn = null;
		PreparedStatement pstmt = null, pstmt2=null, pstmt3=null, pstmt4=null, pstmt5=null, pstmt6=null, pstmt7=null;
		ResultSet rs = null, rs2=null, rs3=null ;
		
		int adddb_num=0;
		String ip=null;
		String client_name=null;
		String service_code=null;
		String adddb_case=null;
		String adddb_code=null;
		String server_code=null;
		Date request_date=null;
		String payment_status=null;
		String amount=null, nonpayment=null;
		int iamount=0, inonpayment=0, ipayment=0;
		
		try{
			conn = dao.getConn();
			
//			지우려는 adddb번호 얻어오기
//         example: "SELECT adddb_num FROM "+'addDB'+ " WHERE "+'addDB_num'+"=?";
			sql ="SELECT adddb_num FROM "+content_db + " WHERE "+ item+"=?";
		
			pstmt2=conn.prepareStatement(sql);
			pstmt2.setString(1, content_code);
			rs2=pstmt2.executeQuery();
			
			System.out.println("오류발생[idcDeleteSericeItemCmd]->"+pstmt2);
			
			if(rs2.next())
				adddb_num=rs2.getInt("adddb_num");
			
			//지우기 전에 adddb에서 필요한 데이터 가져오기.
			sql = "SELECT a.service_code, server_code, adddb_case, adddb_ip,adddb_code, c.client_name, ";
			sql+="a.adddb_request_date , adddb_accountstatus, adddb_amount, adddb_nonpayment, adddb_code, adddb_oneTime, adddb_united ";
			sql+="FROM adddb as a, clientdb as c, servicedb as s WHERE adddb_num=? AND a.client_code=c.client_code AND a.service_code=s.service_code";
			
			pstmt3= conn.prepareStatement(sql);
			pstmt3.setInt(1, adddb_num);
			rs3=pstmt3.executeQuery();
			if(rs3.next()){
				String hcase="기타 부가서비스 ";
				adddb_code = rs3.getString("adddb_code");
				adddb_case = rs3.getString("addDB_case");
				switch(adddb_case)
				{
				case "ip":
				case "IP":
					hcase="IP";
					break;
				}
				request_date = rs3.getDate("a.adddb_request_date");
				payment_status = rs3.getString("adddb_accountstatus");
				
				IdcSetHistory.setHistory(service_code=rs3.getString("a.service_code"), server_code=rs3.getString("server_code"), 
						hcase+"삭제", 
						ip = rs3.getString("addDB_ip"), rs3.getString("addDB_code"),"" ,client_name = rs3.getString("c.client_name"));
				
				amount=rs3.getString("adddb_amount");
				nonpayment=rs3.getString("adddb_nonpayment");
				iamount=Integer.parseInt(amount);
				inonpayment=Integer.parseInt(nonpayment);
				ipayment=iamount-inonpayment;
			}
			
			//deletesub DB로 데이터 이전( 2016년 11월 07일 이 이부분부터 않되는것 확인 )
			sql="INSERT INTO deletesub (service_code, server_code, behavior, request_date, cancel_date, payment_status, note, ";
			sql+="ip, amount, nonpayment, payment, adddb_case, adddb_code, client_name) ";
			sql+="values(?,?,?,?,curdate(),?,? , ?,?,?,?,?,?,?)";
			pstmt5 = conn.prepareStatement(sql);
			pstmt5.setString(1, service_code);
			pstmt5.setString(2, server_code);

			String temp = "";			
			String temp_all = "";
			
			switch (adddb_case)
			{
			case "service":
				temp = "서비스";
				break;
			case "cs":
				temp = "CS";
				break;
			case "VPN":
				temp = "VPN 서비스";
				break;
			case "ip":
				temp = "IP 삭제";
				break;
			case "defence":
				temp = "방어";
				break;
			case "etc":
				temp="기타 부가서비스";
				break;
			default:
				temp = adddb_case;
				break;				
			}
			
			temp_all = temp;
			if(ip != null){
				temp_all = temp_all + " " + ip;
			}
			if(adddb_code != null){
				temp_all = temp_all + "<br>" + adddb_code;
			}

			pstmt5.setString(3, temp_all);
			pstmt5.setDate(4, request_date);
			pstmt5.setString(5, payment_status);
			pstmt5.setString(6,reason);
			pstmt5.setString(7, ip);
			pstmt5.setInt(8, iamount);
			pstmt5.setInt(9, inonpayment);
			pstmt5.setInt(10, ipayment);
			pstmt5.setString(11, adddb_case);
			pstmt5.setString(12, adddb_code);
			pstmt5.setString(13, client_name);			
			pstmt5.executeUpdate();
			
//			IPDB 되돌리기.
			if(content_db.equalsIgnoreCase("addDB"))
			{
				if(adddb_case.equals("ip"))
				{
					IdcSetIP.SetIP("", "", 1, "", "", ip,"x", null, reason);
				}
				else if(adddb_case.equals("defence"))
				{
					defenceDelete(service_code, amount);
				}
				else if(adddb_case.equals("etc"))
				{
					etcDelete(service_code, amount);
				}
			}
			
//			지우려는거 해당 DB서 지워주기( 2016년 11월 07일 이 이부분부터 않되는것 확인 )
			sql = "DELETE FROM "+content_db+" WHERE "+item+"=?";
			pstmt = conn.prepareStatement(sql);			
			pstmt.setString(1, content_code);
			pstmt.executeUpdate();
			
//			cs일 경우 adddb 같이 지워주기.
			if(content_db.equalsIgnoreCase("vpcDB")||content_db.equalsIgnoreCase("kcsDB"))
			{
				sql="DELETE FROM adddb WHERE adddb_num=?";
				pstmt6 = conn.prepareStatement(sql);
				pstmt6.setInt(1, adddb_num);
				pstmt6.executeUpdate();
				
//				csdb 에 있는 사용중이던거 되돌리기.
				sql="UPDATE csdb SET cs_case='0' WHERE cs_name=?";
				pstmt7 = conn.prepareStatement(sql);
				pstmt7.setString(1, adddb_code);
				pstmt7.executeUpdate();
			}
			
//			servicedb 금액 변동 수정
			IdcUpdateServiceAmount.UpdateAmount(amount, service_code, false, adddb_num, nonpayment);

//			디펜스 삭제 아닐경우 amountdb 감소시켜주기.
			if(!adddb_case.equals("defence"))
				setAmountdb(service_code, adddb_case, amount);
		} 
		catch (Exception e) 
		{
			e.printStackTrace();
		}
		finally
		{
			try
			{
				if(rs!=null) rs.close();
				if(pstmt != null) pstmt.close();
				if(rs2!=null) rs2.close();
				if(pstmt2 != null) pstmt2.close();
				if(rs3!=null) rs3.close();
				if(pstmt3 != null) pstmt3.close();
				if(pstmt4 != null) pstmt4.close();
				if(pstmt5 != null) pstmt5.close();				
				if(pstmt6 != null) pstmt6.close();
				if(pstmt7 != null) pstmt7.close();								
				if(conn != null) conn.close();
			} 
			catch (SQLException e) 
			{
				e.printStackTrace();
			}
		}
	}
	
	//amountDB에서 삭제
	private static void etcDelete(String service_code, String amount)
	{
		IdcDAO dao=new IdcDAO();
		
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="UPDATE amountdb set amount_etc=amount_etc-? WHERE service_code=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, amount);
			pstmt.setString(2, service_code);
			pstmt.executeUpdate();
		}
		catch (Exception e) 
		{
			System.out.println("etcDelete 에서의 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("etcDelete 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
	
	//서비스에서 Defence제거 -->일반으로 바꿈
	public static void defenceDelete(String service_code, String amount)
	{
		IdcDAO dao = new IdcDAO();
		Connection conn=null;
		PreparedStatement pstmt=null, pstmt2=null, pstmt3=null, pstmt4=null, pstmt5=null;
		ResultSet rs=null, rs4=null ,rs5=null;
		try	
		{
			//서비스 지우기에 앞서 amountdb 값 설정.
			conn=dao.getConn();
			String sql="UPDATE amountdb SET service_amount=service_amount-amount_defence, amount_defence='0' ";
			sql+="WHERE service_code=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, service_code);
			pstmt.executeUpdate();
			
			//서비스 라인 일반으로 돌리기.
			sql="UPDATE servicedb SET service_line='normal', service_defence='x' WHERE service_code=? ";
			pstmt2=conn.prepareStatement(sql);
			pstmt2.setString(1, service_code);
			pstmt2.executeUpdate();
			
			//서버 위치 받아오기.
			String location="", client_code="";
			sql="SELECT server_location, client_code FROM servicedb as sev, serverdb as ser ";
			sql+="WHERE sev.service_code=? AND sev.server_code = ser.server_code";
			pstmt4 = conn.prepareStatement(sql);
			pstmt4.setString(1, service_code);
			rs4 = pstmt4.executeQuery();
			if(rs4.next())
			{
				location = rs4.getString("server_location");
				client_code = rs4.getString("client_code");
			}
			if(location.equals("tokyo"))
				location="_t";
			else
				location="_c";
			int resel = 0;
			sql="SELECT amount_reseller FROM amountdb WHERE service_code=?";
			pstmt5 = conn.prepareStatement(sql);
			pstmt5.setString(1, service_code);
			rs5=pstmt5.executeQuery();
			if(rs5.next())
				resel = rs5.getInt("amount_reseller");
			
			String normal="normal"+location;
			String defence="defence"+location;
			sql="UPDATE havelist SET "+normal+"="+normal+"+1, "+defence+"="+defence+"-1 ";
			if(resel>0)
				sql+="WHERE client_code='"+client_code+"' ";
			else
				sql+="WHERE client_code='IDCJP'";
			pstmt3 = conn.prepareStatement(sql);
			pstmt3.executeUpdate();
		}
		catch (Exception e) 
		{
			System.out.println("IdcDeleteServiceItemCmd - defenceDelete 에서의 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("IdcDeleteServiceItemCmd - defenceDelete 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
	private static void setAmountdb(String service_code, String adddb_case, String amount)
	{
		IdcDAO dao=new IdcDAO();
		String amountItem="";
		switch(adddb_case)
		{
		case "ip":
			amountItem="amount_ip = amount_ip-'"+amount+"', ";
			break;
		case "cs":
			amountItem="amount_cs = amount_cs-'"+amount+"', ";
			break;
		case "defence":
			amountItem="amount_defence = amount_defence-'"+amount+"'-defence_discount, ";
			break;
		}
		
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="UPDATE amountdb SET "+amountItem+"service_amount=service_amount-'"+amount+"' ";
			sql+="WHERE service_code='"+service_code+"'";
			pstmt =conn.prepareStatement(sql);
			pstmt.executeUpdate();
		}
		catch (Exception e) 
		{
			System.out.println("IdcDeleteServiceItemCmd - setAmountdb 에서의 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("IdcDeleteServiceItemCmd - setAmountdb 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
}
