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.JSONObject;

public class IdcGetLineCodeJSONCmd implements IdcCmd
{
	private IdcDAO dao;
	public IdcGetLineCodeJSONCmd()
	{
		dao = new IdcDAO();
	}
	
	//라인 코드 입력시 중복있나 가져오기
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		String sc = request.getParameter("searchContent");
		if(sc==null)
			sc="";
		ArrayList<String> list = new ArrayList<String>();
		getList(list, sc);
		JSONObject obj = new JSONObject();
		obj.put("a", list);
		
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json");
		
		try
		{
//			System.out.println(obj.toString());
			response.getWriter().write(obj.toString());
		}
		catch (IOException e)
		{
			System.out.println("IdcGetLineCodeJSONCmd - 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 line_code FROM linedb WHERE line_code like '%"+sc+"%' ";
//			System.out.println(sql);
			pstmt =conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				list.add(rs.getString("line_code"));
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcGetLineCodeJSONCmd 에서의 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("IdcGetLineCodeJSONCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
}
