package idc.business.command;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import idc.model.*;

import java.sql.*;

import utility.*;


public class IdcBusinessHandlerCmd implements IdcCmd{
	
	IdcDAO dao = new IdcDAO();
	
	public void execute(HttpServletRequest request, HttpServletResponse response) {
		
		//checkToken 값이 다르면 true반환.
		if(dao.checkToken(request)){
			request.setAttribute("reError", dao.reError);
			return;
		}else{
			//토큰이 같아서 등록성공이 될 경우 토큰을 삭제해 준다.
			request.getSession().removeAttribute("token");
		}
		
		String work_sort = request.getParameter("work_sort");
		String client_name = request.getParameter("client_name");
		String work_content = request.getParameter("work_content");
		String check_date = request.getParameter("work_check_date");
		String end_date = request.getParameter("work_end_date");
		String work_status = request.getParameter("work_status");
		String work_manager = request.getParameter("work_manager");
		
		//Date형으로 형변환
		StringToDate st = new StringToDate();
		
		Date work_check_date;
		if(check_date !=null && check_date !=""){
			work_check_date = st.stringToDate(check_date);
		}else{
			work_check_date = null;
		}
		
		Date work_end_date;
		if(end_date !=null && end_date !=""){
			work_end_date = st.stringToDate(end_date);
		}else{
			work_end_date = null;
		}
		
		//DB입력
		insertWorkDB(work_sort, client_name, work_content, work_check_date, work_end_date, work_status, work_manager);								
	}
	
	public void insertWorkDB(String work_sort, String client_name, String work_content, Date work_check_date, 
			Date work_end_date, String work_status, String work_manager){
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			conn = dao.getConn();
			String sql = "INSERT INTO workDB (work_sort, client_name, work_content, work_check_date, work_end_date, work_status, work_manager) ";
			sql +="values(?, ?, ?, ?, ?, ?, ?)";
			pstmt = conn.prepareStatement(sql);
			
			pstmt.setString(1, work_sort);
			pstmt.setString(2, client_name);
			pstmt.setString(3, work_content);
			pstmt.setDate(4, work_check_date);
			pstmt.setDate(5, work_end_date);
			pstmt.setString(6, work_status);
			pstmt.setString(7, work_manager);
			
			pstmt.executeUpdate();
			
		} catch (Exception e) {
			e.printStackTrace();
		} finally{
			try {
				if(rs != null) rs.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
		
	}

}
