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 IdcGetClientNameCheckJSONCmd implements IdcCmd
{
	private IdcDAO dao;
	public IdcGetClientNameCheckJSONCmd()
	{
		dao = new IdcDAO();
	}
	
	//고객명 중복검사.
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		String sc = request.getParameter("client_name");
		String result = getID(sc);
		JSONObject obj = new JSONObject();
		
		obj.put("a", result);
		
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json");
		try
		{
			response.getWriter().write(obj.toString());
		} 
		catch (IOException e)
		{
			System.out.println("IdcGetClientNameCheckJSONCmd - SendError");
			e.printStackTrace();
		}
	}
	private String getID(String sc)
	{
		String result = "";
		
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT client_name FROM clientdb WHERE client_name=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, sc);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				result = rs.getString("client_name");
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcGetClientNameCheckJSONCmd - getID 에서의 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("IdcGetClientNameCheckJSONCmd - getID 에서의 sqlexception");
				e.printStackTrace();
			}
		}
		
		return result;
	}
}
