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 IdcGetClientNameJSONCmd implements IdcCmd
{
	IdcDAO dao;
	public IdcGetClientNameJSONCmd()
	{
		dao=new IdcDAO();
	}
	//고객명 얻어오기.
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		
		ArrayList<String> list = new ArrayList<String>();
		idcGetClientNameJSONCmd(list, request.getParameter("searchContent"));
		JSONObject obj = new JSONObject();
		JSONArray arr = new JSONArray();
		obj.put("a", list);
		arr.add(obj);
		response.setContentType("application/json");
		response.setCharacterEncoding("utf-8");
		try
		{
			response.getWriter().write(arr.toString());
		} 
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	private void idcGetClientNameJSONCmd(ArrayList<String> list,String s)
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT client_name FROM clientdb WHERE client_name like '%" + s + "%' LIMIT 0,5";
			pstmt =conn.prepareStatement(sql);
			rs=pstmt.executeQuery();
			while(rs.next())
			{
				list.add(rs.getString("client_name"));
			}
		}
		catch (Exception e) 
		{
			System.out.println("idcGetClientNameJSONCmd 에서의 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("idcGetClientNameJSONCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
}
