package idc.json.command;

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

import java.io.IOException;
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 net.sf.json.JSONObject;

public class IdcCheckServerUseJSONCmd implements IdcCmd{

	IdcDAO dao = new IdcDAO();
	//서버 사용중인지 아닌지 확인하여 알려주는 JSON
	public void execute(HttpServletRequest request, HttpServletResponse response){
		String server_code = request.getParameter("server_code");
		
		boolean result = idcServerList(server_code);
		
		//제이슨으로 보내기
		JSONObject obj = new JSONObject();
		obj.put("check_result", result);
		
		response.setCharacterEncoding("UTF-8");
		response.setContentType("Application/json");
		try
		{
			System.out.println(obj.toString());
			response.getWriter().write(obj.toString());
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public boolean idcServerList(String server_code){
						
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		String sql = "";
		int num = 0;
		try {
			conn = dao.getConn();
			sql = "SELECT count(*) AS num FROM serviceDB WHERE server_code=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, server_code);
			rs = pstmt.executeQuery();
						
			if(rs.next()){										
				num = rs.getInt("num");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();				
			}
		}		
		
		if(num == 0){
			return true;
		}else{
			return false;
		}
	}

}
