/*************************************************************************************************
 * 프로그램명 : HttpDocDel.java 프로그램설명 : 집계 문서 삭제 파라미터 작성자 : 작성일 : 변경일 :
 **************************************************************************************************/

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

import java.io.IOException;
import java.io.PrintWriter;

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.TotDoc;
import kr.co.kihyun.beans.entity.util.*;
import kr.co.kihyun.beans.user.HttpSSOLogin;
import kr.co.kihyun.lang.Encoder;
import kr.co.kihyun.lang.MLong;
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.doc.HttpDocDel")
public class HttpDocDel extends HttpServlet {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory.getLogger(HttpDocDel.class);

	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		res.setContentType("text/html;charset=UTF-8");
		PrintWriter out = res.getWriter();
		req.getSession(true);

		/*********** User HttpLogin check ***********/
		if (!HttpSSOLogin.isLogin(req)) {
			String connURL = "location='/totsys/login/login.jsp';";
			out.println(ServletUtil.getJavaScript(connURL));
			return;
		}

		/********** session내의 userId **********/
		String usID = HttpSSOLogin.getLoginID(req);
		/********** parameter value **********/
		String docID = Encoder.toJava(req.getParameter("docID"));
		String userID = Encoder.toJava(req.getParameter("userID"));
		String url = Encoder.toJava(req.getParameter("url"));

		PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
		Transaction tx = pm.currentTransaction();
		try {
			tx.begin();

			TotDoc totDoc = pm.getObjectById(TotDoc.class, MLong.parseLong(docID));
			if (!userID.equals(totDoc.getUser(pm).getId())) {
				out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.totDocDeleteFail")));
				if ("mmprss".equals(url)) // 집계관리자
					out.println(ServletUtil
							.getJavaScript("document.location='/totsys/sysadm/prssbox/doc_list.jsp?docID=" + docID
									+ "';"));
				else
					out.println(ServletUtil
							.getJavaScript("document.location='/totsys/totper/mydocbox/prssbox/doc_list.jsp?docID="
									+ docID + "';"));
				return;
			}

			totDoc.setDeleted("Y");
			if (totDoc.getMasterTotDoc() != null)
				totDoc.setMasterTotDoc(null);
			pm.makePersistent(totDoc);

			tx.commit();
			LOG.info(MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_report.delete") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.success") +" {}, {}, {}", new Object[] {
					usID, req.getRemoteAddr(), docID });
			out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_report.delete") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.success")));
			if ("reg".equals(url)) {
				out.println(ServletUtil
						.getJavaScript("document.location='/totsys/totper/mydocbox/regbox/doc_list.jsp?docID=" + docID
								+ "';"));
			} else if ("form".equals(url)) {
				out.println(ServletUtil
						.getJavaScript("document.location='/totsys/totper/mydocbox/formbox/doc_list.jsp?docID=" + docID
								+ "';"));
			} else {
				out.println(ServletUtil
						.getJavaScript("document.location='/totsys/totper/mydocbox/canclebox/doc_list.jsp?docID="
								+ docID + "';"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error(MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_report.delete") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.fail") + "{}, {}, {}",
					new Object[] { usID, req.getRemoteAddr(), docID });
                        //v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN
//			out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_report.delete") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.fail")));

                        // 수정 : 외부 입력값 필터링
                        String callbackFunc = MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc")
                                            + MoumiConfig.getMessageBundle().getString("moumi.message.tot_report.delete")
                                            + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.fail");
                        String filtered_callbackFunc = callbackFunc.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
                        LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpDocDel.doPost() filtered_callbackFunc={}, Not Test", filtered_callbackFunc);
                        out.println(ServletUtil.getJavaScript(filtered_callbackFunc));
                        //============================================================

			if ("reg".equals(url)) {
				out.println(ServletUtil
						.getJavaScript("document.location='/totsys/totper/mydocbox/regbox/doc_list.jsp?docID=" + docID
								+ "';"));
			} else if ("form".equals(url)) {
				out.println(ServletUtil
						.getJavaScript("document.location='/totsys/totper/mydocbox/formbox/doc_list.jsp?docID=" + docID
								+ "';"));
			} else {
				out.println(ServletUtil
						.getJavaScript("document.location='/totsys/totper/mydocbox/canclebox/doc_list.jsp?docID="
								+ docID + "';"));
			}
		} finally {
			if (tx.isActive())
				tx.rollback();
			pm.close();
		}
	}
}
