/**
 * *******************************************************************************************************
 * 프로그램명 : HttpDocModifyer.java 프로그램설명 : 프로젝트와 관련된 정보를 얻을수 있는 class 작성자 : 강원중
 * 작성일 : 2003.12.10 변경일 : 2003.11.15
 *********************************************************************************************************
 */
package kr.co.kihyun.beans.totsys.doc;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
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 javax.servlet.http.HttpSession;
import kr.co.kihyun.beans.entity.AcceptanceLimitStrategy;
import kr.co.kihyun.beans.entity.AccessAuth;
import kr.co.kihyun.beans.entity.ExecutionCode;
import kr.co.kihyun.beans.entity.MDept;
import kr.co.kihyun.beans.entity.MUser;
import kr.co.kihyun.beans.entity.TotDoc;
import kr.co.kihyun.beans.entity.TotDocAppendType;
import kr.co.kihyun.beans.entity.TotDocProcess;
import kr.co.kihyun.beans.entity.util.*;
import kr.co.kihyun.beans.user.HttpSSOLogin;
import kr.co.kihyun.io.FileUtil;
import kr.co.kihyun.lang.Encoder;
import kr.co.kihyun.lang.MInteger;
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.doc.HttpDocModifyer")
public class HttpDocModifyer extends HttpServlet {

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

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

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
        res.setContentType("text/html;charset=UTF-8");
        PrintWriter out = res.getWriter();
        HttpSession session = req.getSession(true);
        String usID = HttpSSOLogin.getLoginID(req);
        int sysAuth = HttpSSOLogin.getSysAuth(req);

        /**
         * ******** parameter value *********
         */
        Long docID = MLong.parseLong(req.getParameter("docID"), null);
        int execNum = MInteger.parseInt(req.getParameter("execNum"));
        String execDate = MString.checkNull(req.getParameter("execDate"));

        TotDocAppendType appendType = TotDocAppendType.valueOf(MString.checkNull(req.getParameter("appendType"), TotDocAppendType.COPY.toString())); // 파일첨부, 복사, 양식 재사용

        int accAuth = MInteger.parseInt(req.getParameter("accAuth"), 0);
        String stDate = MString.checkNull(req.getParameter("stDate"));
        String stTime = req.getParameter("stTime");
        String edDate = MString.checkNull(req.getParameter("edDate"));
        String edTime = req.getParameter("edTime");
        String title = Encoder.toJava(req.getParameter("title"));
        if(title!=null){
        	title=title.trim();
		}
        String contents = Encoder.toJava(req.getParameter("notify"));
        String prss = MString.checkNull(req.getParameter("prss"), "PRSS");
        String docType = MString.checkNull(req.getParameter("docType"), "PRSS");
        String svrFilenames = Encoder.toJava(req.getParameter("svrFilenames"));
        String redirectURI = req.getParameter("redirectURI");
        String setTheTime = Encoder.toJava(req.getParameter("setTheTime"));

        String acceptanceLimitStrategy = MString.checkNull(req.getParameter("acceptanceLimitStrategy"), "UnlimitStrategy");
        stDate = stDate + " " + stTime + ":00:00";
        edDate = edDate + " " + edTime + ":00:00";
        Date startDate, endDate;
        startDate = endDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
                startDate = sdf.parse(stDate);
            if (acceptanceLimitStrategy.equals("LimitBySubmitDateStrategy") || acceptanceLimitStrategy.equals("UnlimitStrategy")) {
                edDate = "9999-12-30 12:00:00";
            }
            endDate = sdf.parse(edDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        kr.co.kihyun.beans.entity.Board mBoard = null;
        TotDoc totDoc = null;
        MUser mUser = null;

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

        PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
        Transaction tx = pm.currentTransaction();
//		ObjectManager om = ((JDOPersistenceManager) tx.getPersistenceManager()).getObjectManager(); // jeus 6 proplem
        try {
            tx.begin();
            TotDoc pc = pm.getObjectById(TotDoc.class, docID);
            totDoc = pm.detachCopy(pc);
            String DocUserID=pc.getUser(pm).getId();
            mUser = pm.getObjectById(MUser.class, usID);
            if (sysAuth == MoumiConfig.TOTPER && !usID.equals(DocUserID)&&docID<1700000000) {
                out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc")
                        + MoumiConfig.getMessageBundle().getString("moumi.message.popup.modifyFail")));
                out.println(ServletUtil.getJavaScript("location.href='/totsys/totper/mydocbox/prssbox/doc_modify.jsp?docType="
                        +docType+"&docID="+ docID + "';"));
                return;
            }

            SimpleDateFormat execDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            ExecutionCode execCode = null;
            //시행번호 입력 필요에 의해 주석달음.
            //2014.09.01 LIM
            if (execNum > 0 && !MString.isNull(execDate)) {
                ExecutionCode curExecCode = pc.getExecutionCode();
                execCode = new ExecutionCode(curExecCode.getDeptName() == null ? pm.getObjectById(MDept.class, pc.getDept()).getName() : curExecCode.getDeptName(), execNum, execDateFormat.parse(execDate));
                pc.setExecutionCode(execCode);//시행번호 입력
             }
            //미진행자료에서 넘어온 것중 연계자료일경우 유저 및 오너 업데이트
            if(docID>=1700000000&&prss.equals("PRSS")&&docType.equals("REG")){
            	pc.setUser(mUser);
            }
            pc.setStartDate(startDate);
            pc.setEndDate(endDate);
            pc.setRegDate(new Date());
            pc.setAppendType(appendType);
            pc.setAccessAuth(AccessAuth.values()[accAuth]);

            AcceptanceLimitStrategy acptLimitStrategy = AcceptanceLimitStrategy.create(acceptanceLimitStrategy, MLong.parseLong(req.getParameter("submitLimit"), 10000L));
            acptLimitStrategy.setProcess(TotDocProcess.valueOf(MString.checkNull(req.getParameter("prss"), pc.getProcess(pm).name())));
            pc.setAcceptanceLimitStrategy(acptLimitStrategy);

            FileUtil.putInFiles(svrFilenames, pc);

            mBoard = pc.getBoard();
            mBoard.setTitle(title);
            mBoard.setContents(contents);
            mBoard.setTotDoc(pc);
            pc.setName(title);
            pm.makePersistent(mBoard);
            pm.makePersistent(pc);


//			om.postCommit(); // jeus 6 problem
            tx.commit();


            FileUtil.getBoardAttachmentsFileNames(mBoard.getId(), req, true);
           // FileUtil.delUpFiles(svrFilenames,pc); //디렉토리에서 파일 삭제
            LOG.info("{}{}{}: {}, {}, {}", new Object[]{
                MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.information"),
                MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.change"),
                MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.success"),
                usID, req.getRemoteAddr(), docID
            });
            out.println("<script> alert(\"성공적으로 기본정보를 변경 하였습니다.\")</script>");


            String allowURL[] = { "/totsys/totper/mydocbox/prssbox/doc_list.jsp" };
            ArrayList arr = new ArrayList();
            for ( int i = 0; i < allowURL.length; i++ )
            arr.add(allowURL[i]);

            String url = "/totsys/totper/mydocbox/prssbox/doc_list.jsp";
            if (url != null && !url.contains("http://") ) {
                url = url.replaceAll("\r", "").replaceAll("\n", "");

                if ( arr.contains(url) ) {
                   //v2. 1.HTTP 응답분할 : Update by KWON,HAN
//                   url += "?docType="+prss;
//                   res.sendRedirect(url);

                    if (prss != null) {
                        // 수정 : 외부 입력값 필터링
                        String filtered_prss = prss.replaceAll("\r","").replaceAll("\n","");
                        //LOG.debug("v2 1.HTTP 응답분할 : HttpDocModifyer.doPost() filtered_prss={} : Test OK ", filtered_prss);
                        url += "?docType="+filtered_prss;
			res.sendRedirect(url);
                    }
                    //========================================
                }
            }
            //=================================================================================

        } catch (Exception e) {
            e.printStackTrace();
            LOG.error("{}{}{}: {}, {}, {}, {}", new Object[]{
                MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.information"),
                MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.change"),
                MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.fail"),
                e.getMessage(), usID, req.getRemoteAddr(), docID
            });
            out.println("<script> alert(\"기본정보 변경을 실패하였습니다.\")</script>");
            //v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN
//            out.println(ServletUtil.redirect((String) session.getAttribute("modifyFailTargetURI")));

            // 수정 : 외부 입력값 필터링
            String url = (String) session.getAttribute("modifyFailTargetURI");
            String filtered_url = url.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
            LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpDocModifyer.doPost() filtered_url={}, Not Test", filtered_url);
            out.println(ServletUtil.getJavaScript(filtered_url));
            //============================================================

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