package idc.main.command;

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

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 IdcShareBoardModifyCmd implements IdcCmd
{
	IdcDAO dao;
	public IdcShareBoardModifyCmd()
	{
		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");
		}
		
		IdcShareBoardDBDTO dto = new IdcShareBoardDBDTO();
		setDTO(dto, request);
		idcShareBoardModifyCmd(dto);
	}
	private void setDTO(IdcShareBoardDBDTO dto, HttpServletRequest request)
	{
		dto.setContent(request.getParameter("content"));
		dto.setFilename(request.getParameter("filename"));
		dto.setId(request.getParameter("id"));
		dto.setNum(Integer.parseInt(request.getParameter("num")));
		dto.setTitle(request.getParameter("title"));
		
		System.out.println(dto.getTitle());
	}
	private void idcShareBoardModifyCmd(IdcShareBoardDBDTO dto)
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			int index=1;
			conn=dao.getConn();
			String sql="UPDATE shareboarddb SET title=?,content=?,filename=?,write_date=curdate() WHERE num=?";
			pstmt =conn.prepareStatement(sql);
			pstmt.setString(index++, dto.getTitle());
			pstmt.setString(index++, dto.getContent());
			pstmt.setString(index++, dto.getFilename());
			pstmt.setInt(index++, dto.getNum());
			pstmt.executeUpdate();
		}
		catch (Exception e) 
		{
			System.out.println("idcShareBoardModifyFormCmd 에서의 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("idcShareBoardModifyFormCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
}
