package idc.line.command;

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

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 IdcLineDeleteCmd implements IdcCmd
{
	private IdcDAO dao;
	
	public IdcLineDeleteCmd()
	{
		dao = new IdcDAO();
	}
	
	//라인 삭제
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		//checkToken 값이 다르면 true반환.
		if(dao.checkToken(request))
		{
			request.setAttribute("reError", dao.reError);
			return;
		}
		else
		{
			//토큰이 같아서 등록성공이 될 경우 토큰을 삭제해 준다.
			request.getSession().removeAttribute("token");
		}
		
		int line_num = Integer.parseInt(request.getParameter("line_num"));
		ArrayList<String> list = new ArrayList<String>();
		
		//사용중인 ip가 있을경우 지울 수 없게 한다.
		if(checkIP(line_num, list))
		{
			//라인 지우기
			deleteLine(line_num);
		}
		else
		{
			//사용중인 리스트 전송.
			request.setAttribute("UseList", list);
		}
	}
	
	//ip 사용중인지 아닌지 판단.
	private boolean checkIP(int line_num, ArrayList<String> list)
	{
		System.out.println("df");
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		boolean result=true;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT ip_address, ip_user FROM ipdb WHERE line_num=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setInt(1, line_num);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				if(!rs.getString("ip_user").equalsIgnoreCase(""))
				{
					list.add(rs.getString("ip_address"));
					result=false;
				}
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcLineDeleteCmd - checkIP 에서의 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("IdcLineDeleteCmd - checkIP 에서의 sqlexception");
				e.printStackTrace();
			}
		}
		return result;
	}
	private void deleteLine(int line_num)
	{
		Connection conn=null;
		PreparedStatement pstmt=null, pstmt2=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="DELETE FROM linedb WHERE line_num=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setInt(1, line_num);
			pstmt.executeUpdate();
			
			sql="DELETE FROM ipdb WHERE line_num=?";
			pstmt2=conn.prepareStatement(sql);
			pstmt2.setInt(1, line_num);
			pstmt2.executeUpdate();
		}
		catch (Exception e) 
		{
			System.out.println("IdcLineDeleteCmd - deleteLine 에서의 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("IdcLineDeleteCmd - deleteLine 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
}
