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.JSONArray;

public class IdcGetServerYJSONCmd implements IdcCmd
{
	IdcDAO dao;
	
	public IdcGetServerYJSONCmd()
	{
		dao = new IdcDAO();
	}
	//사용중인 서버리스트 가져오기(15개)
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		String sc = request.getParameter("data");
		// TODO Auto-generated method stub
		JSONArray jArray = new JSONArray();
		idcGetServerYJSONCmd(jArray, sc);
		response.setContentType("application/json");
		response.setCharacterEncoding("utf-8");
		try
		{
			response.getWriter().write(jArray.toString());
		} 
		catch (IOException e)
		{
			System.out.println("IdcGetServerYJSONCmd - json 보내기 오류");
			e.printStackTrace();
		}
	}
	private void idcGetServerYJSONCmd(JSONArray jArray, String sc)
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT server_code, server_cost, server_spec, server_ram, server_hdd FROM serverdb ";
			sql+="WHERE server_use_status=? AND server_code like '%"+sc+"%' limit 0,15";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, "y");
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				String a[] = new String[5];
				a[0] = rs.getString("server_code");
				a[1] = rs.getString("server_cost");
				a[2] = rs.getString("server_spec");
				a[3] = rs.getString("server_ram");
				a[4] = rs.getString("server_hdd");
						
				jArray.add(a);
			}
		}
		catch (Exception e) 
		{
			System.out.println("idcGetServerYJSONCmd 에서의 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("idcGetServerYJSONCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
}
