package idc.service.command;

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

import idc.model.*;

import java.sql.*;

public class IdcKCSWriteCmd implements IdcCmd{
	
	IdcDAO dao = new IdcDAO();
	
	//kcs정보 받아오기
	public void execute(HttpServletRequest request, HttpServletResponse response) {
		String service_code = request.getParameter("service_code");
		
		IdcKCSDTO ikd;
		ikd = getKCSDTO(service_code);
		request.setAttribute("kcs_list", ikd);					
	}
	
	public IdcKCSDTO getKCSDTO(String service_code){
		IdcKCSDTO ikd = new IdcKCSDTO();
		
		Connection conn = null;
		PreparedStatement pstmt = null, pstmt1 = null;
		ResultSet rs = null, rs1 = null;
		String sql;
		int num = 0;
		
		try {			
			conn = dao.getConn();
			sql = "SELECT COUNT(kcs_code) AS num FROM kcsDB 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, service_admin, c.client_name, s.client_code, service_ip, server_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=?";
										
			pstmt1 = conn.prepareStatement(sql);
			pstmt1.setString(1, service_code);					
			rs1 = pstmt1.executeQuery();
			
			if(rs1.next()){				
				ikd.setService_code(service_code);
				ikd.setService_line(rs.getString("service_line"));
				ikd.setService_admin(rs.getString("service_admin"));
				ikd.setClient_name(rs.getString("client_name"));
				ikd.setService_ip(rs.getString("service_ip"));
				ikd.setServer_code(rs.getString("server_code"));
								
				String kcs_code = "KCS-"+ String.format("%03d", num);				
				ikd.setKcs_code(kcs_code);
				ikd.setClient_code(rs.getString("client_code"));								
			}		
			
		} catch (Exception e) {			
			e.printStackTrace();						
		} finally{
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(rs1 != null) rs1.close();
				if(pstmt1 != null) pstmt1.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
		return ikd;
	}

}