package idc.json.command;

import idc.model.IdcCmd;
import idc.model.IdcDAO;
import idc.model.IdcGearDBDTO;

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 java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import com.google.gson.JsonArray;

public class IdcServerListJSONCmd implements IdcCmd
{
	IdcDAO dao;
	public IdcServerListJSONCmd()
	{
		dao = new IdcDAO();
	}
	
	//입력한 서버정보(cpu명, 모델명, 가격) 가져오기.
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		response.setContentType("application/json");
		response.setCharacterEncoding("utf-8");
		
		try
		{
			response.getWriter().write(createJson().toString());
		}
		catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	private JSONArray createJson()
	{
		JSONArray jArray = new JSONArray();
		JSONArray jTemp = null;
		JSONObject jObj = null;
		ArrayList<IdcGearDBDTO>  list = idcServerListJSONCmd();
		for(int i=0;i<list.size();i++)
		{
			jObj = new JSONObject();
			jObj.put("id", list.get(i).getProcess());

			jTemp = new JSONArray();
			jTemp .add(list.get(i));
			jObj.put("a", jTemp);
			jArray.add(jObj);
		}
		System.out.println(jArray.toString());
		return jArray;
	}
	private ArrayList<IdcGearDBDTO> idcServerListJSONCmd()
	{
		ArrayList<IdcGearDBDTO> list = new ArrayList<IdcGearDBDTO>();
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		
		String checkPage="";
		boolean flag=false;
		IdcGearDBDTO dto = new IdcGearDBDTO();
		try	
		{
			conn=dao.getConn();
			String sql="SELECT process, spec, cpuname, (price*10000) as price FROM gearlist ORDER BY firarr ASC, secarr ASC ";
			pstmt =conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				if(!checkPage.equals(rs.getString("process")))
				{
					
					if(flag)
					{
						list.add(dto);
						dto = new IdcGearDBDTO();
					}
					dto.setProcess(checkPage=rs.getString("process"));
					flag=true;
				}
				dto.setSpec(rs.getString("spec"));
				dto.setCpuname(rs.getString("cpuname"));
				dto.setCost(rs.getString("price"));
			}
			list.add(dto);
		}
		catch (Exception e) 
		{
			System.out.println("idcNewServerListFormCmd 에서의 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("idcNewServerListFormCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
		return list;
	}
}
