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

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.moumi.MoumiConfig;
import kr.co.kihyun.text.html.ServletUtil;
import kr.co.kihyun.lang.MLong;
import kr.co.kihyun.lang.MString;
import kr.co.kihyun.lang.MInteger;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebServlet("/servlet/kr.co.kihyun.beans.totsys.doc.HttpDocDeleter")
public class HttpDocDeleter extends HttpServlet {

	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory.getLogger(HttpDocDeleter.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)) {
			// login 성공후 되돌아올 주소
			String connURL = "location='/totsys/login/login.jsp';";
			out.println(ServletUtil.getJavaScript(connURL));
			return;
		}
		String usID = HttpSSOLogin.getLoginID(req);
		int sysAuth = HttpSSOLogin.getSysAuth(req);

		String docID = Encoder.toJava(req.getParameter("docID"));
		String userID = Encoder.toJava(req.getParameter("userID"));
		String url = Encoder.toJava(req.getParameter("url"));
		String findOption = Encoder.toJava(MString.checkNull(req.getParameter("findOption")));
		String findWord = Encoder.toJava(MString.checkNull(req.getParameter("findWord")));
		int accAuth = MInteger.parseInt(req.getParameter("accAuth"));

		PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
		Transaction tx = pm.currentTransaction();
		TotDoc totDoc = null;
		String[] docIDList = null;
		docIDList = docID.split(",");

		try {
			tx.begin();
			for (int i = 0; i < docIDList.length; i++) {
				totDoc = pm.getObjectById(TotDoc.class, MLong.parseLong(docIDList[i]));
				if (sysAuth > MoumiConfig.TOTPER) {
					totDoc.setDeleted("Y");
					if (totDoc.getMasterTotDoc() != null)
						totDoc.setMasterTotDoc(null);
				} else {
					if (userID.equals(totDoc.getUser(pm).getId())) {
						totDoc.setDeleted("Y");
						if (totDoc.getMasterTotDoc() != null)
							totDoc.setMasterTotDoc(null);
					}
				}
				pm.makePersistent(totDoc);
			}
			tx.commit();
			LOG.info(MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.formDoc") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_report.delete") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.success") +" {}, {}, {}",
			new Object[] { usID, req.getRemoteAddr(), docID });
			if ("form".equals(url)) {
				out.println(ServletUtil
						.getJavaScript("document.location='/totsys/totper/mydocbox/formbox/doc_list.jsp?docID=" + docID
								+ "';"));
			} else if ("reuseform".equals(url)) {
				out.println(ServletUtil
						.getJavaScript("document.location='/totsys/totper/mydocbox/regbox/popup_form_list.jsp?findOption="
								+ findOption + "&findWord=" + findWord + "&accAuth=" + accAuth + "';"));
			}
		} catch (Exception e) {
			e.printStackTrace();
			LOG.error(MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.formDoc") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_report.delete") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.fail") +" {}, {}, {}",
					new Object[] { usID, req.getRemoteAddr(), docID });
			out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.deleteAuth")));
			if ("form".equals(url)) {
				out.println(ServletUtil
						.getJavaScript("document.location='/totsys/totper/mydocbox/formbox/doc_list.jsp?docID=" + docID
								+ "';"));
			} else if ("reuseform".equals(url)) {
                                //v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN
//				out.println(ServletUtil
//						.getJavaScript("document.location='/totsys/totper/mydocbox/regbox/popup_form_list.jsp?findOption="
//								+ findOption + "&findWord=" + findWord + "&accAuth=" + accAuth + "';"));

                                // 수정 : 외부 입력값 필터링
                                String callbackFunc = "document.location='/totsys/totper/mydocbox/regbox/popup_form_list.jsp?findOption="
								+ findOption + "&findWord=" + findWord + "&accAuth=" + accAuth + "';";
                                String filtered_callbackFunc = callbackFunc.replaceAll("<","").replaceAll(">","").replaceAll(",","");
                                LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpDocDeleter.doPost() filtered_callbackFunc={}, Not Test", filtered_callbackFunc);
				out.println(ServletUtil.getJavaScript(filtered_callbackFunc));
                                //============================================================
			}
		} finally {
			if (tx.isActive())
				tx.rollback();
			pm.close();
		}
	}
}
