package idc.service.command;

import idc.model.IdcCmd;
import idc.model.IdcDAO;
import idc.model.IdcIPDBDTO;

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;

public class IdcIPChangeFormCmd implements IdcCmd
{
	private IdcDAO dao = new IdcDAO();
	
	//아이피 변경
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		String mkworker = request.getParameter("mkworker");	
		String service_code = request.getParameter("service_code");
		String main_ip = getIP(service_code);
		ArrayList<IdcIPDBDTO> list = new ArrayList<IdcIPDBDTO>();
		setList(list, service_code);
		
		request.setAttribute("service_code", service_code);
		request.setAttribute("main_ip", main_ip);
		request.setAttribute("mkworker", mkworker);
		request.setAttribute("sub", list);
				
	}
		
	private void setList(ArrayList<IdcIPDBDTO> list, String service_code)
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT * FROM ipdb WHERE service_code=? AND ip_case2='ip_sub' ORDER BY ip_address ASC";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, service_code);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				IdcIPDBDTO dto = new IdcIPDBDTO();
				dto.setIp_address(rs.getString("ip_address"));
				list.add(dto);
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcIPChangeFormCmd 에서의 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("IdcIPChangeFormCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
	private String getIP(String service_code)
	{
		String ip = "";
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT service_ip FROM servicedb WHERE service_code=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(1, service_code);
			rs = pstmt.executeQuery();
			if(rs.next())
			{
				ip = rs.getString("service_ip");
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcIPChangeFormCmd 에서의 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("IdcIPChangeFormCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
		
		return ip;
	}
}
