package idc.json.command;

import idc.model.IDCserviceListDTO;
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.JSONObject;

public class IdcGetUseServerCodeJSONCmd implements IdcCmd
{
	private IdcDAO dao;
	public IdcGetUseServerCodeJSONCmd()
	{
		dao = new IdcDAO();
	}
	
	//cs적용시킬 서버 가져오기.
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		ArrayList<String> list = new ArrayList<String>();
		String sc = request.getParameter("server_code");
		getList(list,sc);
		
		JSONObject obj = new JSONObject();
		obj.put("a", list);
		
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json");
		try
		{
			response.getWriter().write(obj.toString());
		} 
		catch (IOException e)
		{
			System.out.println("IdcGetUseServerCodeJSONCmd - sendError");
			e.printStackTrace();
		}
	}
	
	private void getList(ArrayList<String> list, String sc)
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT DISTINCT server_code FROM servicedb WHERE cs_count>0 AND server_code like '%"+sc+"%' ";
			sql+="LIMIT 0,15";
			pstmt =conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				System.out.println(rs.getString("server_code"));
				list.add(rs.getString("server_code"));
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcGetUseServerCodeJSONCmd 에서의 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("IdcGetUseServerCodeJSONCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
	
	

}
