package idc.main.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 IdcGearDeleteCmd implements IdcCmd
{
	IdcDAO dao;
	public IdcGearDeleteCmd()
	{
		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 firarr = Integer.parseInt(request.getParameter("firarr"));
		int secarr = Integer.parseInt(request.getParameter("secarr"));
		delDB(firarr, secarr);
		arrayDB(firarr);
	}
	
	private void arrayDB(int firarr)
	{
		Connection conn=null;
		PreparedStatement pstmt=null, pstmt2=null;
		ResultSet rs=null;
		ArrayList<Integer> arr = new ArrayList<Integer>();
		try	
		{
			conn=dao.getConn();
			String sql="SELECT secarr FROM gearList WHERE firarr=? ORDER BY firarr ASC, secarr ASC";
			pstmt =conn.prepareStatement(sql);
			pstmt.setInt(1, firarr);
			rs = pstmt.executeQuery();
			while(rs.next())
			{
				arr.add(rs.getInt("secarr"));
			}
			//삭제한 후 데이터 다시 정렬.
			sql="UPDATE gearlist SET secarr=? WHERE firarr=? AND secarr=?";
			pstmt2=conn.prepareStatement(sql);
			for(int i=0;i<arr.size();i++)
			{
				pstmt2.setInt(1, i);
				pstmt2.setInt(2, firarr);
				pstmt2.setInt(3, arr.get(i));
				pstmt2.executeUpdate();
			}
		}
		catch (Exception e) 
		{
			System.out.println("IdcGearDeleteCmd - arrDB 에서의 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("IdcGearDeleteCmd - arrDB 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
	private void delDB(int firarr, int secarr)
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="DELETE FROM gearList WHERE firarr=? AND secarr=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setInt(1, firarr);
			pstmt.setInt(2, secarr);
			pstmt.executeUpdate();
		}
		catch (Exception e) 
		{
			System.out.println("IDCLINEIPWRITECMD 에서의 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("IDCLINEIPWRITECMD 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
}
