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 IdcBusinessGetClientNameCmd implements IdcCmd
{
	private IdcDAO dao;
	
	public IdcBusinessGetClientNameCmd()
	{
		dao = new IdcDAO();
	}
	
	//business에서 고객명 얻어오기위한 JSON
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		ArrayList<String> list = new ArrayList<String>();
		ArrayList<String> list2 = new ArrayList<String>();
		
		getList(list, list2);
		
		JSONObject obj = new JSONObject();
		obj.put("cName", list);
		obj.put("mName", list2);
		
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json");
		try
		{
			response.getWriter().write(obj.toString());
		} 
		catch (IOException e)
		{
			System.out.println("IdcBusinessGetClientNameCmd - jsonSend 오류");
			e.printStackTrace();
		}
	}
	
	private void getList(ArrayList<String> list, ArrayList<String> list2)
	{
		Connection conn=null;
		PreparedStatement pstmt=null, pstmt2=null;
		ResultSet rs=null, rs2=null;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT DISTINCT(client_name) as n FROM deliverydb";
			pstmt =conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				list.add(rs.getString("n"));
			}
			
			sql="SELECT DISTINCT(delivery_manager) as n FROM deliverydb";
			pstmt2=conn.prepareStatement(sql);
			rs2=pstmt2.executeQuery();
			while(rs2.next())
			{
				list2.add(rs2.getString("n"));
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcBusinessGetClientNameCmd 에서의 exception");
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(conn!=null) conn.close();
				if(rs!=null)rs.close();
				if(pstmt!=null)pstmt.close();
				if(rs2!=null)rs2.close();
				if(pstmt2!=null)pstmt2.close();
			}
			catch (SQLException e) 
			{
				System.out.println("IdcBusinessGetClientNameCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
}
