package idc.json.command;

import idc.model.IdcCmd;
import idc.model.IdcDAO;
import idc.model.IdcLinkDBDTO;

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.JSONArray;
import net.sf.json.JSONObject;

public class IdcGetLinkJSONCmd implements IdcCmd
{
	IdcDAO dao;
	public IdcGetLinkJSONCmd()
	{
		dao = new IdcDAO();
	}
	
	//퀵메뉴 리스트 가져오기
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		ArrayList<IdcLinkDBDTO> list = new ArrayList<IdcLinkDBDTO>();
		idcGetLinkJSONCmd(list);
		
		JSONObject obj = new JSONObject();
		JSONArray arr = new JSONArray();
		obj.put("linkList", list);
		arr.add(obj);
		
		response.setContentType("application/json");
		response.setCharacterEncoding("utf-8");
		try
		{
			//System.out.println(arr.toString());
			response.getWriter().write(arr.toString());
		}
		catch (IOException e)
		{
			System.out.println("IdcGetLinkJSONCmd - json 에서의 send오류");
			e.printStackTrace();
		}
	}
	private void idcGetLinkJSONCmd(ArrayList<IdcLinkDBDTO> list)
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT * FROM linkdb";
			pstmt =conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				IdcLinkDBDTO dto = new IdcLinkDBDTO();
				dto.setLink(rs.getString("link"));
				dto.setName(rs.getString("name"));
				dto.setPower(rs.getInt("power"));
				
				list.add(dto);
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcGetLinkJSONCmd 에서의 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("IdcGetLinkJSONCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
}
