package idc.json.command;

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;
import utility.IdcSetCS;
import idc.model.IdcCmd;
import idc.model.IdcDAO;

public class IdcAddCSJSONCmd implements IdcCmd
{
	private IdcDAO dao;
	
	public IdcAddCSJSONCmd()
	{
		dao = new IdcDAO();
	}
	
	//cs 칸수증가(안쓰임)
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		String service_code = request.getParameter("service_code");
		String server_code = request.getParameter("server_code");
		JSONObject obj = new JSONObject();
		obj.put("a", createCS(service_code, server_code));
		
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json");
		try
		{
			response.getWriter().write(obj.toString());
		} 
		catch (IOException e)
		{
			System.out.println("IdcADDCSJSONCmd SEND 오류");
			e.printStackTrace();
		}
	}
	
	//cs칸수 증가시키기.
		public boolean createCS(String service_code, String server_code)
		{
			boolean result = false;
			Connection conn=null;
			PreparedStatement pstmt=null, pstmt2=null;
			ResultSet rs=null;
			String cs_name="";
			try	
			{
				conn=dao.getConn();
				String sql="SELECT service_cs, cs_count FROM servicedb WHERE service_code = ?";
				pstmt =conn.prepareStatement(sql);
				pstmt.setString(1, service_code);
				rs = pstmt.executeQuery();
				if(rs.next())
				{
					if(Integer.parseInt(rs.getString("cs_count"))<8)
					{	
						int count=Integer.parseInt(rs.getString("cs_count"))+1;
						cs_name=rs.getString("service_cs");
						cs_name = cs_name.concat("-".concat(Integer.toString(count)));
						
						System.out.println(cs_name);
						IdcSetCS.setCS(service_code, server_code, cs_name);

						sql="UPDATE servicedb SET cs_count=cs_count+1 WHERE service_code=?";
						pstmt2 = conn.prepareStatement(sql);
						pstmt2.setString(1, service_code);
						pstmt2.executeUpdate();
						result=true;
					}
				}
			}
			catch (Exception e) 
			{
				System.out.println("createCS 에서의 exception");
				e.printStackTrace();
			}
			finally
			{
				try 
				{
					if(conn!=null) conn.close();
					if(pstmt!=null)pstmt.close();
					if(pstmt2!=null)pstmt2.close();
					if(rs!=null)rs.close();
				}
				catch (SQLException e) 
				{
					System.out.println("createCS 에서의 sqlexception");
					e.printStackTrace();
				}
			}
			return result;
		}
}
