/**********************************************************************************
 * 프로그램명 : FileDelete.java 작 성 자 : 강원중 작 성 일 : 2003. 7.23 최신변경일 : 2013. 1.11
 ***********************************************************************************/

package kr.co.kihyun.beans.totsys.board;

import java.io.File;
//import java.io.FileNotFoundException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;
//import java.util.Map;
import java.util.Map.Entry;
import javax.jdo.PersistenceManager;
import javax.jdo.Transaction;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import kr.co.kihyun.beans.entity.Board;
import kr.co.kihyun.beans.entity.TotDoc;
import kr.co.kihyun.beans.entity.TotReport;
import kr.co.kihyun.beans.entity.util.PMF;
import kr.co.kihyun.beans.user.HttpSSOLogin;
import kr.co.kihyun.db.CommonDBManager;
import kr.co.kihyun.io.IUploadable;

import kr.co.kihyun.lang.Encoder;
import kr.co.kihyun.lang.MLong;
import kr.co.kihyun.lang.MString;
import kr.co.kihyun.moumi.MoumiConfig;
import kr.co.kihyun.text.html.ServletUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebServlet("/servlet/kr.co.kihyun.beans.totsys.board.HttpFileDeleteDir")
public class HttpFileDeleteDir extends HttpServlet {
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory.getLogger(HttpFileDeleteDir.class);

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

		res.setContentType("text/html");
		res.setContentType("text/html;charset=UTF-8");
		PrintWriter out = res.getWriter();

		String svrFilename = Encoder.toJava(req.getParameter("fileList"));
        String filtered_svrFilename = svrFilename.replaceAll("\r","").replaceAll("\n","");
		String boardGroupID = req.getParameter("boardGroupID");
		Long docID = MLong.parseLong(req.getParameter("docID"));
		Long reportID = MLong.parseLong(req.getParameter("reportID"));
		Long boardID = MLong.parseLong(req.getParameter("boardID"));
		String mode = MString.checkNull(req.getParameter("mode"));
        String usID = HttpSSOLogin.getLoginID(req);//20170829 추가 by wonseok Lee.
        String dtID = MString.checkNull(req.getParameter("dtID"));
		LOG.debug("delete file list: {}, docID: {}, reportID: {}, boardID: {}",
		new Object[] {svrFilename, docID, reportID, boardID});

		try {
			if (svrFilename != null) {

				// 3.디렉토리 경로 조작(getParameter)_CWE-22/23/36 : Add by KWON,HAN
				LOG.debug("svrFilename: {}", svrFilename);
				if (svrFilename.contains("..") || svrFilename.contains("/")) { // 특수문자열  검증
					LOG.debug("HttpFileDeleteDir doPost ===");
					LOG.debug("3.디렉토리 경로 조작(getParameter)_CWE-22/23/36 : Not Test {}",svrFilename);
					LOG.debug("===========================");
					return;
				}
				// +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

				if ("csv".equals(mode)) {
					File file = new File(MoumiConfig.getCsvFileRoot(), svrFilename);
					if (!file.delete())
						throw new IOException(svrFilename + " delete failed.");
				}
				else {
					PersistenceManager pm = PMF.get().getPersistenceManager();
					Transaction tx = pm.currentTransaction();
					try {
						tx.begin();
						TotReport totReport = pm.getObjectById(TotReport.class, reportID);
						totReport.clearAttachment();
						pm.makePersistent(totReport);

						tx.commit();
					} catch (Exception e) {
						if (tx.isActive())
							tx.rollback();
					} finally{
						pm.close();
					}
				}


				//20170814 추가 by wonseok Lee. 접수자료 > 자료입력 > 파일제출에서  파일 삭제시 해당 디렉토리( MoumiConfig.getFileDirectory()/DOCID/REPORTID/DeptID)에서 파일을 삭제 한다.
			    File path = new File(MoumiConfig.getFileDirectory()+"/"+Long.toString(docID)+"/"+reportID+"/"+dtID+"/"+filtered_svrFilename);
				if(path.isFile()) {
			    	if(!path.delete()) {
			    		LOG.debug("파일이 존재하나 삭제에 실패했습니다..");
			    	}
				}else{
					LOG.error("서버에 파일이 존재하지 않습니다.");
				}


				CommonDBManager acdbm1=new CommonDBManager();
		        StringBuilder sql = new StringBuilder(250);
		        try{
			        sql.append("UPDATE MOUMI_TOT_REPORT SET ATTACHMENTS_PATH = REPLACE(ATTACHMENTS_PATH, ? ,'')  WHERE ID = ? ");
			        acdbm1.execUpdate(sql.toString(), svrFilename+";", reportID);
			        acdbm1.pstmt.close();

			        sql.delete(0, sql.length());
			        sql.append("UPDATE MOUMI_TOT_REPORT_VERSION SET ATTACHMENTS_PATH = REPLACE(ATTACHMENTS_PATH, ? ,'') WHERE REPORT_ID = ? AND ID=(SELECT MAX(ID) FROM MOUMI_TOT_REPORT_VERSION  WHERE DEL_TYPE = 'N' AND REPORT_ID = ? )");
			        acdbm1.execUpdate(sql.toString(), svrFilename+";", reportID, reportID);
			        acdbm1.pstmt.close();
			        acdbm1.commit();
		        }catch(Exception e){
		        	acdbm1.rollback();
		        }finally{
		        	acdbm1.execClose();
		        }

            }

		//44.적절하지 않은 예외처리(광범위예외클래스)_CWE-754 : Update by YOUNGJUN,CHO
		} catch (IOException ioex) {
                        ioex.printStackTrace();
        //================================================

		} catch (Exception ex) {
			LOG.error("File delete failed: {}", ex.getMessage());
            out.println(
                		ServletUtil.alert(
                			MoumiConfig.getMessageBundle().getString("moumi.message.popup.fileDeleteFail"))
                			+ ": " + ex.getMessage());

            //v2. 1.HTTP 응답분할 : Update by KWON,HAN
//			res.sendRedirect("/totsys/common/inc/board/doc/write_file_upload_dir.jsp?execMode=del&svrFilename="
//			+ svrFilename + "&usrFilename=" + svrFilename + "&boardGroupID=" + boardGroupID + "&docID="
//			+ docID + "&boardID=" + boardID + "&mode=" + mode + "&reportID=" + reportID);

            //========================================
		} finally{
            if (svrFilename != null) {
                // 수정 : 외부 입력값 필터링
                LOG.debug("v2 1.HTTP 응답분할 : HttpFileDeleteDir.doPost() filtered_svrFilename={} : Test OK ", filtered_svrFilename);
                res.sendRedirect("/totsys/common/inc/board/doc/write_file_upload_dir.jsp?execMode=del&svrFilename="
                    + filtered_svrFilename + "&usrFilename=" + filtered_svrFilename + "&boardGroupID=" + boardGroupID + "&docID="
                    + docID + "&boardID=" + boardID + "&mode=" + mode + "&reportID=" + reportID+ "&dtID=" + dtID );
             }
		}
	}
}
