package idc.main.command;

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

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

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

//import org.apache.catalina.util.Enumerator;
//import org.apache.tomcat.util.net.SecureNioChannel.ApplicationBufferHandler;

//import sun.reflect.ReflectionFactory.GetReflectionFactoryAction;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.FileRenamePolicy;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

import java.io.File;
import java.io.IOException;

public class IdcShareBoardWriteCmd implements IdcCmd
{
	IdcDAO dao;
	private static final int MAX_POST_SIZE = 10*1024*1024;
	//1024 byte -> 1024 kb -> 10 mb(현재)
	public IdcShareBoardWriteCmd()
	{
		dao = new IdcDAO();
	}
	
	//공용페이지 등록
	@Override
	public void execute(HttpServletRequest request, HttpServletResponse response)
	{
		IdcShareBoardDBDTO dto = setDTO();
		request.setAttribute("check", setFile(dto,request));
	}
	
	private boolean setFile(IdcShareBoardDBDTO dto, HttpServletRequest request)
	{
		boolean check = false;
		String saveDirectory = this.getClass().getResource("").getPath()+"../../../../../FileUpload";
		String encoding="utf-8";
		FileRenamePolicy policy = new DefaultFileRenamePolicy();
		saveDirectory = saveDirectory.replaceAll("%20", " ");
				
		String fileName = null;
		
		MultipartRequest multipartRequest=null;
		try
		{
			multipartRequest = new MultipartRequest(request,saveDirectory, MAX_POST_SIZE, encoding ,policy);
//			System.out.println(saveDirectory);
			dto.setContent(multipartRequest.getParameter("content"));
			dto.setTitle(multipartRequest.getParameter("title"));
			Enumeration enumer = multipartRequest.getFileNames();
			String file = (String)enumer.nextElement();
			dto.setFilename(fileName = multipartRequest.getFilesystemName(file));
			File f = multipartRequest.getFile("fileName");
			dto.setFilepath(f.getAbsolutePath());
			dto.setFilesize(f.length());
		} 
		catch (IOException e)
		{
			e.printStackTrace();
		}
		
		if(fileName==null)
			System.out.println("파일 업로드 실패!");
		else
		{
			check = true;
			
			IdcMemberDBDTO temp = (IdcMemberDBDTO)request.getSession().getAttribute("member");
			dto.setId(temp.getId());
			dto.setFilename(fileName);
			
			idcShareBoardWriteCmd(dto);
		}
		return check;
	}
	private void idcShareBoardWriteCmd(IdcShareBoardDBDTO dto)
	{
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			int index=1;
			conn=dao.getConn();
			String sql="INSERT INTO shareboarddb (num,content,filename,write_date,title,id,filepath,filesize)";
			sql+=" values(?,?,?,curdate(),?,?,?,?)";
			pstmt =conn.prepareStatement(sql);
			pstmt.setInt(index++, dto.getNum());
			pstmt.setString(index++, dto.getContent());
			pstmt.setString(index++, dto.getFilename());
			pstmt.setString(index++, dto.getTitle());
			pstmt.setString(index++, dto.getId());
			pstmt.setString(index++, dto.getFilepath());
			pstmt.setLong(index++, dto.getFilesize());
			pstmt.executeUpdate();
		}
		catch (Exception e) 
		{
			System.out.println("idcShareBoardWriteCmd 에서의 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("idcShareBoardWriteCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
	}
	private IdcShareBoardDBDTO setDTO()
	{
		IdcShareBoardDBDTO dto = new IdcShareBoardDBDTO();
		
		Connection conn=null;
		PreparedStatement pstmt=null;
		ResultSet rs=null;
		try	
		{
			conn=dao.getConn();
			String sql="SELECT COUNT(*) as a FROM shareboarddb";
			pstmt =conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
		
			if(rs.next())
			{
				dto.setNum(rs.getInt("a")+1);
			}
		}
		catch (Exception e) 
		{
			System.out.println("idcShareBoardWriteCmd 에서의 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("idcShareBoardWriteCmd 에서의 sqlexception");
				e.printStackTrace();
			}
		}
		return dto;
	}
}
