/**
 * ***********************************************************************************************
 * 프로그램명 : HttpDocDel.java 프로그램설명 : 집계 문서 삭제 파라미터 작성자 : 작성일 : 변경일 :
 *************************************************************************************************
 */
package kr.co.kihyun.beans.totsys.totper;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
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.TotDocType;
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.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.totper.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();

        /**
         * ********* User HttpSSOLogin check **********
         */
        if (!HttpSSOLogin.isLogin(req)) {
            // login 성공후 되돌아올 주소
            String connURL = "location='/totsys/login/login.jsp';";
            out.println(ServletUtil.getJavaScript(connURL));
            return;
        }

        String usID = HttpSSOLogin.getLoginID(req);
        String docID = Encoder.toJava(req.getParameter("docID"));
        String userID = HttpSSOLogin.getLoginID(req);
        String url = Encoder.toJava(req.getParameter("url"));
        String docType = MString.checkNull(req.getParameter("docType"));
        String strPage = (String) Encoder.toJava(req.getParameter("strPage"));
        String findOption = MString.checkNull(Encoder.toJava(req.getParameter("findOption")));
//        String findWord = MString.checkNull(Encoder.toJava(req.getParameter("findWord")));
        String findWord = MString.checkNull(req.getParameter("findWord"));
        String stDate = MString.checkNull(req.getParameter("stDate"));
        String edDate = MString.checkNull(req.getParameter("edDate"));

        int sysAuth = HttpSSOLogin.getSysAuth(req);
        TotDoc totDoc = null;

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

            if (!"endDoc".equals(url)) {
                totDoc = pm.getObjectById(TotDoc.class, MLong.parseLong(docID));
            }

            if (!"endDoc".equals(url) && !userID.equals(totDoc.getUser(pm).getId()) && sysAuth == MoumiConfig.TOTPER) {
                out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.totDocDeleteFail")));
              //out.println(ServletUtil.getJavaScript("document.location='/totsys/totper/mydocbox/prssbox/doc_list.jsp?docType=" + docType + "';"));
                out.println(ServletUtil.getJavaScript("document.location='/totsys/totper/mydocbox/prssbox/doc_list.jsp?docType=" + docType + "&strPage="+ strPage + "&findOption="+ findOption + "&findWord="+ findWord + "&stDate=" + stDate + "&edDate=" + edDate + "';"));
                return;
            }

            if (!"endDoc".equals(url)) {
                totDoc.setDeleted("Y");
                if (totDoc.getMasterTotDoc() != null) {
                    totDoc.setMasterTotDoc(null);
                }
                pm.makePersistent(totDoc);
            } else {
                String[] docIDList = null;
                docIDList = docID.split(",");
                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);
                        }
                        pm.makePersistent(totDoc);
                    } 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") + 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.getJavaScript("document.location='/totsys/totper/mydocbox/prssbox/doc_list.jsp?docType=" + docType + "';"));
            out.println(ServletUtil.getJavaScript("document.location='/totsys/totper/mydocbox/prssbox/doc_list.jsp?docType=" + docType + "&strPage="+ strPage + "&findOption="+ findOption + "&findWord="+ URLEncoder.encode(MString.checkNull(findWord), "UTF-8") + "&stDate=" + stDate + "&edDate=" + edDate + "';"));

//            System.out.println("url location ::: " + stDate + "  ::  " + edDate );
//            out.println(ServletUtil.getJavaScript("document.location='/totsys/totper/mydocbox/prssbox/doc_list.jsp?docType=" + docType + "&strPage="+ strPage + "';"));
        } 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});
            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")));
            //out.println(ServletUtil.getJavaScript("document.location='/totsys/totper/mydocbox/prssbox/doc_list.jsp?docType=" + docType + "';"));
            //v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN
//            out.println(ServletUtil.getJavaScript("document.location='/totsys/totper/mydocbox/prssbox/doc_list.jsp?docType=" + docType + "&strPage="+ strPage + "&findOption="+ findOption + "&findWord="+ findWord + "';"));

            // 수정 : 외부 입력값 필터링
            String callbackFunc = "document.location='/totsys/totper/mydocbox/prssbox/doc_list.jsp?docType=" + docType + "&strPage="+ strPage + "&findOption="+ findOption + "&findWord="+ findWord + "&stDate=" + stDate + "&edDate=" + edDate + "';";
            String filtered_callbackFunc = callbackFunc.replaceAll("<","").replaceAll(">","").replaceAll(",","");
            LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpDocDel.doPost() filtered_callbackFunc={}, Not Test", filtered_callbackFunc);
            out.println(ServletUtil.getJavaScript(filtered_callbackFunc));
            //========================================

        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            pm.close();
        }
    }
}
