package idc.cupon.command;

import idc.model.IdcCmd;
import idc.model.IdcCuponDBDTO;
import idc.model.IdcDAO;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

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

public class IdcCuponWriteCmd implements IdcCmd 
{
	private IdcDAO dao;
	
	public IdcCuponWriteCmd() 
	{
		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");
		}
		
		ArrayList<IdcCuponDBDTO>list  = (ArrayList<IdcCuponDBDTO>)request.getSession().getAttribute("IdcServiceList");
		String[] cupon_current = request.getParameterValues("cupon_current");
		String[] server_upgrade = request.getParameterValues("server_upgrade");
		String[] cupon_note = request.getParameterValues("cupon_note");
		
		IdcCuponDBDTO dto;
		for(int i=0; i<list.size(); i++)
		{
			dto = list.get(i);
			dto.setCupon_current(Integer.parseInt(cupon_current[i]));
			dto.setServer_upgrade(server_upgrade[i]);
			dto.setCupon_note(cupon_note[i]);
		}
		
		idcCuponWriteCmd(list);
	}
	
	private void idcCuponWriteCmd(ArrayList<IdcCuponDBDTO> list)
	{
		Connection conn=null;
		PreparedStatement pstmt=null, pstmt2=null;
		ResultSet rs=null;
		int num=0;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT COUNT(*) AS cupon_num FROM cupondb";
			pstmt =conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			if(rs.next())
				num = rs.getInt("cupon_num");
			IdcCuponDBDTO dto;
			for(int i=0;i<list.size();i++)
			{
				dto = list.get(i);
				sql="INSERT INTO cupondb( cupon_num, service_code, cupon_request_date, cupon_current, cupon_use, cupon_result, server_upgrade, cupon_end_date, cupon_note) ";
				sql+="values(?,?,curdate(),?,?,?,?,?,?)";
				pstmt2 = conn.prepareStatement(sql);
				pstmt2.setInt(1, ++num);
				pstmt2.setString(2, dto.getService_code());
				pstmt2.setInt(3, dto.getCupon_current());
				pstmt2.setInt(4, 0);
				pstmt2.setInt(5, dto.getCupon_current());
				pstmt2.setString(6, dto.getServer_upgrade());
				pstmt2.setDate(7, dto.getCupon_end_date());
				pstmt2.setString(8, dto.getCupon_note());
				
				pstmt2.executeUpdate();
			}
		}
		catch (Exception e) 
		{
			System.out.println("IDCCUPONWRITECMD 에서의 exception");
			e.printStackTrace();
		}
		finally
		{
			try 
			{
				if(conn!=null) conn.close();
				if(pstmt!=null)pstmt.close();
				if(pstmt2!=null)pstmt2.close();
				if(rs!=null)rs.close();
			}
			catch (SQLException e) 
			{
				System.out.println("IDCCUPONWRITECMD 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}

}
