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 idc.model.*;

public class IdcVPCWriteCmd implements IdcCmd{

	IdcDAO dao = new IdcDAO();
	
	//vpc-cs추가창 정보 불러오기
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		
		String service_code = request.getParameter("service_code");
		IdcVPCDTO ivd;
		ivd = getVPCDTO(service_code);		
		request.setAttribute("vpc_list", ivd);
				
	}
	
	public IdcVPCDTO getVPCDTO(String service_code){
		IdcVPCDTO ivd = new IdcVPCDTO();
		
		Connection conn = null;
		PreparedStatement pstmt = null, pstmt2=null;
		ResultSet rs = null, rs2=null;
		String sql;
		int num = 0;
		
		
		try {
			conn = dao.getConn();
			
			sql = "SELECT COUNT(vpc_code) AS num FROM vpcDB WHERE service_code=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, service_code);
			rs = pstmt.executeQuery();
			if(rs.next()){
				num = rs.getInt("num") + 1;
			}
			
			sql = "SELECT service_line, c.client_name, service_ip, s.server_code, c.client_code, s.service_code ";
			sql += "from serviceDB as s Inner join clientDB as c ";
			sql += "where s.client_code = c.client_code and s.service_code=?";
						
			pstmt2 = conn.prepareStatement(sql);
			pstmt2.setString(1, service_code);
			rs2 = pstmt2.executeQuery();
			
			if(rs2.next()){				
				ivd.setService_code(service_code);
				ivd.setService_line(rs2.getString("service_line"));
				ivd.setClient_name(rs2.getString("client_name"));
				ivd.setService_ip(rs2.getString("service_ip"));
				ivd.setServer_code(rs2.getString("server_code"));
				ivd.setClient_code(rs2.getString("client_code"));
				
				String vpc_code =  rs2.getString("server_code");
				String []temp = vpc_code.split("-");
				vpc_code = temp[1] +"-"+ num;
				ivd.setVpc_code(vpc_code);
			}
			
			
		} 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(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return ivd;
	}
	

}
