package idc.board.command;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import idc.model.IdcDAO;
import idc.model.IdcMemberDBDTO;

public class NoteBookWriteCmd implements BoardCmd{
	private IdcDAO daodao = new IdcDAO();
	BoardDAO dao = new BoardDAO();
	
	public void execute(HttpServletRequest request, HttpServletResponse response) {
		
		//checkToken 값이 다르면 true반환.
		if(daodao.checkToken(request)){
			request.setAttribute("reError", daodao.reError);
			return;
		}else{
			//토큰이 같아서 등록성공이 될 경우 토큰을 삭제해 준다.
			request.getSession().removeAttribute("token");
		}
				
		//세션값으로 이름 불러옴
		IdcMemberDBDTO d1to = (IdcMemberDBDTO)request.getSession().getAttribute("member");
		String name = d1to.getName();				
		String content = request.getParameter("content");
		
		//글쓰기
		writeNote(name, content);
		
	}
	
	public void writeNote(String name, String content){
						
		Connection conn = null;
		PreparedStatement pstmt = null, pstmt1 = null;
		ResultSet rs = null;
		int num = 1;
		
		try {
			conn = dao.getConn();
			String sql = "SELECT IFNULL(MAX(num), 0) + 1 AS NUM FROM noteDB";
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			
			if(rs.next()){
				num = rs.getInt("num");
			}
						
			sql = "INSERT INTO noteDB (num, name, content, write_date, write_time) values(?, ?, ?, curdate(), curtime())";
			pstmt1 = conn.prepareStatement(sql);
			
			pstmt1.setInt(1, num);
			pstmt1.setString(2, name);						
			pstmt1.setString(3, content);			
			
			pstmt1.executeUpdate();
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(pstmt1 != null) pstmt1.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

}
