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 utility.IdcGetClientNameCode;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

public class IdcGetIPListJSONCmd implements IdcCmd
{
	IdcDAO dao;
	
	public IdcGetIPListJSONCmd()
	{
		dao = new IdcDAO();
	}
	
	//ip얻어오기.
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		ArrayList<String> list = new ArrayList<String>();
		String sc = request.getParameter("getIP");
		String name = request.getParameter("getClient_Name");
		if(name==null)
		{
			name = IdcGetClientNameCode.getClientName(request.getParameter("getClient_Code"));
			if(name==null)
				name="";
		}
		idcGetIPListJSONCmd(list, sc,name);
		
		response.setContentType("application/json");
		response.setCharacterEncoding("utf-8");
		
		JSONObject obj = new JSONObject();
		obj.put("a", list);
		JSONArray arr = new JSONArray();
		arr.add(obj);
		
		try
		{
			response.getWriter().write(arr.toString());
		}
		catch (IOException e)
		{
			System.out.println("idcGetIPListJSONCmd - JSON 전송오류");
			e.printStackTrace();
		}
		
	}
	private void idcGetIPListJSONCmd(ArrayList<String> list, String sc, String name)
	{
		Connection conn=null;
		PreparedStatement pstmt=null ;
		ResultSet rs=null ;
		try	
		{
			conn=dao.getConn();
			String sql = "SELECT ip_address FROM ipdb ";
			sql+="WHERE ip_able=? AND ip_address like '%"+sc+"%' ";
			sql+="ORDER BY ip1 ASC, ip2 ASC, ip3 ASC, ip4 ASC LIMIT 0,20";
			
			pstmt =conn.prepareStatement(sql);
			pstmt.setInt(1, 1);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				list.add(rs.getString("ip_address"));
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcGetIPListJSONCmd 에서의 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("IdcGetIPListJSONCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
}














