package idc.main.command;

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

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;

public class IdcMemberModifyCmd implements IdcCmd 
{
	IdcDAO dao;
	
	public IdcMemberModifyCmd() 
	{
		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");
		}
		
		
		IdcMemberDBDTO dto = setDTO(request);
		if(idcMemberModifyCmd(dto))
		{
			dto.passDel();
			request.getSession().setAttribute("member", dto);
		}
	}
	
	private boolean idcMemberModifyCmd(IdcMemberDBDTO dto)
	{
		boolean success = false;
		boolean check=false;
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		String pass="";

		if(dto.getPass()!="" & dto.getPass()!=null)
		{
			pass=", pass=MD5(?) ";
			check=true;
		}
		
		try	
		{
			int index=1;
			conn=dao.getConn();
			String sql="UPDATE memberdb SET name=?, num=?, rank=?, phone=?, location=?, note=?, part=?"+pass;
			sql+=" WHERE id=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(index++, dto.getName());
			pstmt.setString(index++, dto.getNum());
			pstmt.setString(index++, dto.getRank());
			pstmt.setString(index++, dto.getPhone());
			pstmt.setString(index++, dto.getLocation());
			pstmt.setString(index++, dto.getNote());
			pstmt.setString(index++, dto.getPart());
			if(check)
				pstmt.setString(index++,dto.getPass());
			pstmt.setString(index++, dto.getId());
			
			pstmt.executeUpdate();
			success = true;
		}
		catch (Exception e) 
		{
			System.out.println("idcMemberModifyCmd 에서의 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("idcMemberModifyCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
		return success;
	}
	//dto데이터 삽입
	private IdcMemberDBDTO setDTO(HttpServletRequest request)
	{
		IdcMemberDBDTO dto = new IdcMemberDBDTO();
		
		dto.setId(getPara(request, "member_id"));
		dto.setLocation(getPara(request, "location"));
		dto.setName(getPara(request, "name"));
		dto.setNote(getPara(request, "note"));
		dto.setNum(getPara(request, "num"));
		dto.setPass(getPara(request, "pass"));
		dto.setPhone(getPara(request, "phone"));
		dto.setRank(getPara(request, "rank"));
		dto.setPart(getPara(request, "part"));
		return dto;
	}
	//requst.getpara쓰기 귀찮아서 만듦
	private String getPara(HttpServletRequest request, String value)
	{
		return request.getParameter(value);
	}
}
