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 java.util.ArrayList;

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

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class IdcGetServerCodeJSONCmd implements IdcCmd
{
	IdcDAO dao;
	
	public IdcGetServerCodeJSONCmd()
	{
		dao = new IdcDAO();
	}
	
	//장비명 가져오기(중복확인)
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		ArrayList<String> list = new ArrayList<String>();
		String code = request.getParameter("server_code");
		idcGetServerCodeJSONCmd(list, code);
		response.setContentType("application/json");
		response.setCharacterEncoding("utf-8");
		JSONObject obj = new JSONObject();
		JSONArray arr =new JSONArray();
		
		obj.put("code", list);
		arr.add(obj);
		
		try
		{
//			System.out.println(arr.toString());
			response.getWriter().write(arr.toString());
		} 
		catch (IOException e)
		{
			System.out.println("IdcGetServerCodeJSONCmd-JSON 샌드 오류");
			e.printStackTrace();
		}
	}
	private void idcGetServerCodeJSONCmd(ArrayList<String> list, String code)
	{
		Connection conn=null;
		PreparedStatement pstmt=null, pstmt2=null;
		ResultSet rs=null, rs2=null;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT server_code FROM serverdb WHERE server_code like '%"+code+"%' ";
			sql+="LIMIT 0,5";
//			System.out.println(sql);
			pstmt =conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				list.add(rs.getString("server_code"));
			}
			
			sql="SELECT server_code FROM servicedb WHERE server_code=?";
			pstmt2=conn.prepareStatement(sql);
			pstmt2.setString(1, code);
			rs2 = pstmt2.executeQuery();
			if(rs2.next())
				list.add(rs2.getString("server_code"));
		}
		catch (Exception e) 
		{
			System.out.println("IdcGetServerCodeJSONCmd 에서의 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("IdcGetServerCodeJSONCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
}
















