package idc.business.command;

import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

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

import utility.StringToDate;
import idc.model.*;

public class IdcBusinessDeliveryHandleCmd 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 delivery_sort = request.getParameter("delivery_sort");
		String client_name = request.getParameter("client_name");
		String delivery_content = request.getParameter("delivery_content");
		String check_date = request.getParameter("delivery_check_date");
		String end_date = request.getParameter("delivery_end_date");
		String delivery_status = request.getParameter("delivery_status");
		String delivery_manager = request.getParameter("delivery_manager");
		
		//날짜 String에서 Date로 형변환
		StringToDate st = new StringToDate();				
		Date delivery_check_date;
		if(check_date !=null && check_date !=""){
			delivery_check_date = st.stringToDate(check_date);
		}else{
			delivery_check_date = null;
		}				
		Date delivery_end_date;
		if(end_date != null && end_date != ""){
			delivery_end_date = st.stringToDate(end_date);
		}else{
			delivery_end_date = null;
		}
		
		//DB입력
		insertdeliveryDB(delivery_sort, client_name, delivery_content, delivery_check_date, delivery_end_date, delivery_status, delivery_manager);		
	}
	
	public void insertdeliveryDB(String delivery_sort, String client_name, String delivery_content, Date delivery_check_date, 
			Date delivery_end_date, String delivery_status, String delivery_manager){
		
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		
		try {
			conn = dao.getConn();
			String sql = "INSERT INTO deliveryDB (delivery_sort, client_name, delivery_content, delivery_check_date, delivery_end_date, delivery_status, delivery_manager) ";
			sql +="values(?, ?, ?, ?, ?, ?, ?)";
			pstmt = conn.prepareStatement(sql);
			
			pstmt.setString(1, delivery_sort);
			pstmt.setString(2, client_name);
			pstmt.setString(3, delivery_content);
			pstmt.setDate(4, delivery_check_date);
			pstmt.setDate(5, delivery_end_date);
			pstmt.setString(6, delivery_status);
			pstmt.setString(7, delivery_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();
			}
		}		
	}
	
}