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 javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

public class IdcGetKCSCodeJSONCmd implements IdcCmd
{
	private IdcDAO dao;
	public IdcGetKCSCodeJSONCmd()
	{
		dao = new IdcDAO();
	}
	
	//kcs 입력한것 같은거 있나 없나 얻어오기.
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		JSONObject obj = new JSONObject();
		obj.put("a", getCode(request.getParameter("sc")));
		
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json");
		
		try
		{
			response.getWriter().write(obj.toString());
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private String getCode(String sc)
	{
		String result = "";
		
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT cs_name FROM csdb WHERE cs_name=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, sc);
			rs = pstmt.executeQuery();
			if(rs.next())
				result = rs.getString("cs_name");
		}
		catch (Exception e) 
		{
			System.out.println("IdcGetKCSCodeJSONCmd 에서의 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("IdcGetKCSCodeJSONCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
		
		return result;
	}
}
