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 java.util.HashMap;
import java.util.List;
import java.util.Map;

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

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

import com.google.gson.Gson;

public class IdcJsonIDCmd implements IdcCmd
{
	IdcDAO dao;
	Connection conn = null;
	PreparedStatement pstmt = null;
	ResultSet rs = null;
	public IdcJsonIDCmd()
	{
		dao = new IdcDAO();
	}
	
	//입력한 글자를 토대로 사용중인 id가져오기.
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		response.setContentType("application/json");
		response.setCharacterEncoding("utf-8");
		int selectJson = Integer.parseInt(request.getParameter("selectJson"));
		String inputData = request.getParameter("data");
		List list = null;
		switch(selectJson)
		{
		case 1:
			list = idcJsonID(inputData);
			break;
		}
		
		try
		{
			for(int i=0;i<list.size();i++)
			{
				IdcJsonIDData data = (IdcJsonIDData)list.get(i);
			}
			response.getWriter().write(new Gson().toJson(list));
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	private List<IdcJsonIDData> idcJsonID(String inputData)
	{
		List<IdcJsonIDData> list = new ArrayList<IdcJsonIDData>();
		String sql ="SELECT id FROM memberdb WHERE id like '"+inputData+"%' Limit 0,10";
		rs = getRs(sql);
		try
		{
			while(rs.next())
			{
				IdcJsonIDData idData = new IdcJsonIDData();
				idData.setId(rs.getString("id"));
				list.add(idData);
			}
		} 
		catch (Exception e) 
		{
			System.out.println("IdcJsonID 에서의 exception");
			e.printStackTrace();
		}
		finally
		{
			closeProp();
		}
		return list;
	}
	private void closeProp()
	{
		try
		{
			if(conn!=null) conn.close();
			if(pstmt!=null)pstmt.close();
			if(rs!=null)rs.close();
		} 
		catch (SQLException e)
		{
			System.out.println("IdcJsonID 에서의 sqlexception");
			e.printStackTrace();
		}
	}
	private ResultSet getRs(String sql)
	{
		try	
		{
			conn=dao.getConn();
			pstmt =conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
		}
		catch (Exception e) 
		{
			System.out.println("IdcJsonID 에서의 exception");
			e.printStackTrace();
		}
		return rs;
	}
}
