/*************************************************************************************************
 * 프로그램명 : HttpDocRegister.java 프로그램설명 : 집계문서 등록자 작성자 : 강원중 작성일 : 2004.06.07 변경일 : 2003.11.30
 **************************************************************************************************/

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

//import kr.co.kihyun.beans.ecross.ECrossInterface;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
//import java.text.ParseException;
import java.text.SimpleDateFormat;
//import java.util.ArrayList;
import java.util.Date;
//import java.util.HashSet;
//import java.util.List;
//import java.util.Set;

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.ecross.VCMCCMC2013;

import kr.co.kihyun.beans.entity.AcceptanceLimitStrategy;
import kr.co.kihyun.beans.entity.AccessAuth;
import kr.co.kihyun.beans.entity.Category;
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.TotDocType;
//import kr.co.kihyun.beans.entity.TotReport;
import kr.co.kihyun.beans.entity.TotTable;
import kr.co.kihyun.beans.entity.util.*;
import kr.co.kihyun.beans.totsys.report.ReportUpdate;
import kr.co.kihyun.beans.user.GroupView;
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.moumi.doc.MDoc;
import kr.co.kihyun.moumi.doc.table.MTableRemaker;
import kr.co.kihyun.moumi.doc.table.item.MItemInfo;
import kr.co.kihyun.text.html.ServletUtil;
import kr.co.kihyun.text.html.TagFilter;
import org.datanucleus.ObjectManager;
import org.datanucleus.jdo.JDOPersistenceManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
//import java.io.File;
//import java.io.FileInputStream;
//import java.util.Arrays;
@WebServlet("/servlet/kr.co.kihyun.beans.totsys.doc.HttpDelFile")
public class HttpDelFile extends HttpServlet {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger LOG = LoggerFactory.getLogger(HttpDelFile.class);

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws ServletException, IOException {
		res.setContentType("text/html;charset=UTF-8");
		HttpSession session = req.getSession(true);
		if (req.getMethod().equals("HEAD"))
			return;
		PrintWriter out = res.getWriter();

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

		/********** session내의 userId **********/
		String usID = HttpSSOLogin.getLoginID(req);
		String dtID = HttpSSOLogin.getDeptID(req);
		/********** parameter value **********/
		String docName = URLDecoder.decode(req.getParameter("docName"), "UTF-8");
		int execNum = MInteger.parseInt(req.getParameter("execNum"));
		String execDate = MString.checkNull(req.getParameter("execDate"));
		LOG.debug("docName: {}", docName);
		LOG.debug("execNum: {}, execDate: {}", execNum, execDate);
		TotDocAppendType appendType = TotDocAppendType.valueOf(MString.checkNull(req.getParameter("appendType"),
				TotDocAppendType.COPY.toString())); // 파일첨부, 복사, 양식 재사용
		String handyName = Encoder.toJava(MString.checkNull(req.getParameter("handyName")));
		Long repDocID = MLong.parseLong(req.getParameter("repDocID"), null);
		int defItemSize = MInteger.parseInt(req.getParameter("defItemSize"), 10);
		int accAuth = MInteger.parseInt(req.getParameter("accAuth"), 0);	// 프로젝트 권한설정관련
		int totRange = MInteger.parseInt(MString.checkNull(req.getParameter("totRange")), 0);
		int tableType = MInteger.parseInt(Encoder.toJava(req.getParameter("tableType")), 0);
		String acceptanceLimitStrategy = MString.checkNull(req.getParameter("acceptanceLimitStrategy"), "UnlimitStrategy");
		String prss = MString.checkNull(req.getParameter("prss"), "PRSS");
		Long submitLimit = MLong.parseLong(req.getParameter("submitLimit"), 10000L);
		LOG.debug("acceptanceLimitStrategy: {}", acceptanceLimitStrategy);
		String itemNames = Encoder.toJava(req.getParameter("itemNames"));
		LOG.debug("itemNames: {}", itemNames);
		String itemSizes = Encoder.toJava(req.getParameter("itemSizes"));
		String itemExprs = Encoder.toJava(req.getParameter("itemExprs"));
		String itemDescs = Encoder.toJava(req.getParameter("itemDescs"));

		String itemTypes = Encoder.toJava(req.getParameter("itemTypes"));
		String tableNums = Encoder.toJava(req.getParameter("tableNums"));
		String colNums = Encoder.toJava(req.getParameter("colNums"));
		String rowNums = Encoder.toJava(req.getParameter("rowNums"));
		String tableTypes = Encoder.toJava(req.getParameter("tableTypes"));
		int docGroupID = MInteger.parseInt(req.getParameter("docGroupID"));
		String isFromFormBox = MString.checkNull(req.getParameter("isFromFormBox"));
		Date stDate, edDate;
		stDate = edDate =  new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
		String deptIDs = Encoder.toJava(req.getParameter("deptIDs"));
		String userIDs = Encoder.toJava(req.getParameter("userIDs"));
		String deptTypes = Encoder.toJava(req.getParameter("deptTypes"));

		String[] deptIDList = deptIDs.split(",");
		String[] typeList = deptTypes.split(",");

		int all = typeList.length;
		StringBuilder dts = new StringBuilder();
		StringBuilder uss = new StringBuilder();

		for (int a = 0; a < all; a++) {
			if (typeList[a].equals("user")) {
				if (uss.toString().length() == 0) {
					uss.append(deptIDList[a]);
				} else {
					if (!uss.toString().contains(deptIDList[a])) {
						uss.append(",");
						uss.append(deptIDList[a]);
					}
				}
			} else if (typeList[a].equals("group")) {
				if (new GroupView().getUserUserDeptUserID(deptIDList[a]) != "") {
					if (uss.toString().length() == 0) {
						uss.append(new GroupView().getUserUserDeptUserID(deptIDList[a]));
					} else {
						if (!uss.toString().contains(new GroupView().getUserUserDeptUserID(deptIDList[a]))) {
							uss.append(",");
							uss.append(new GroupView().getUserUserDeptUserID(deptIDList[a]));
						}
					}
				}

				if (new GroupView().getUserDeptDeptID(deptIDList[a]) != "") {
					if (dts.toString().length() == 0) {
						dts.append(new GroupView().getUserDeptDeptID(deptIDList[a]));
					} else {
						if (!dts.toString().contains(new GroupView().getUserDeptDeptID(deptIDList[a]))) {
							dts.append(",");
							dts.append(new GroupView().getUserDeptDeptID(deptIDList[a]));
						}
					}
				}
			} else {
				if (dts.toString().length() == 0) {
					dts.append(deptIDList[a]);
				} else {
					if (!dts.toString().contains(deptIDList[a])) {
						dts.append(",");
						dts.append(deptIDList[a]);
					}
				}
			}
		}
		deptIDs = dts.toString();
		userIDs = uss.toString();

		MItemInfo itemInfo = new MItemInfo();
		itemInfo.itemInfo(itemNames, itemSizes, itemExprs, itemDescs,
				itemTypes, tableNums, colNums, rowNums, defItemSize);
		String docForm = (String) session.getAttribute("docForm");
		docForm = MTableRemaker.remake(TagFilter.getConvertForm(docForm), itemInfo); // 셀정의 수식을 엑셀저장시 적용되게 해줌
		String usrFilenames = URLDecoder.decode(MString.checkNull(req.getParameter("usrFilenames")), "UTF-8");
		String svrFilenames = URLDecoder.decode(MString.checkNull(req.getParameter("svrFilenames")), "UTF-8");
		String title = Encoder.toJava(MString.checkNull(req.getParameter("title")));
		title = TagFilter.convertMeta(title);
		if (MString.isNull(title))
			title = docName;
		String notify = (String) session.getAttribute("notify");
                
      //if ((execNum < 0 && !MString.isNull(execDate)) || (execNum > 0 && MString.isNull(execDate))) {
      //out.println(ServletUtil.alert("시행번호 형식이 올바르지 않습니다.\n번호 혹은 시행일이 올바른지 확인해 주시기 바랍니다."));
      //return;
      //}
              
		TotDoc repDoc = null;
		MDept userDept = null;
		MUser mUser = null;
		TotDoc newDoc = null;

		MPersistenceManager moumiPm = new MPersistenceManager(PMF.get().getPersistenceManager());
		Transaction tx = moumiPm.currentTransaction();
		MPersistenceManager eCrossPm = new MPersistenceManager(PMF.get("ECROSS").getPersistenceManager());
		Transaction eCrossTx = eCrossPm.currentTransaction();
		ObjectManager om = ((JDOPersistenceManager) tx.getPersistenceManager()).getObjectManager(); // jeus 6 proplem

        
		try {
			LOG.info("PersistenceManager begin DEL");
			tx.begin();
			repDoc = repDocID == null ? null : moumiPm.getObjectById(TotDoc.class, repDocID);
			userDept = moumiPm.getObjectById(MDept.class, dtID);
			mUser = moumiPm.getObjectById(MUser.class, usID);
			LOG.debug("usID from session: {}", usID);

			SimpleDateFormat execDateFormat = new SimpleDateFormat("yyyy-MM-dd");
			ExecutionCode execCode = null;
			if (execNum > 0 && !MString.isNull(execDate))
				execCode = new ExecutionCode(mUser.getUpperDept(moumiPm).getName(), execNum, execDateFormat.parse(execDate));
			LOG.debug("prss: {}", prss);
			newDoc = docRegist(moumiPm, docName, execCode, handyName, mUser, stDate, edDate,
					AccessAuth.asAccessAuth(accAuth), TotDoc.TotRange.asTotRange(totRange), docForm, repDoc,
					docGroupID, userDept, appendType, acceptanceLimitStrategy, submitLimit, prss);
			TotTable newDocTable = tableRegist(moumiPm, defItemSize, tableType, tableTypes, newDoc);
			moumiPm.makePersistentAll(itemInfo.toTotItemList(newDoc));

			String[] stringDeptIDArray = deptIDs.split(",");
                        
                        //v2 23.정수형 오버플로우 (배열인덱스)_CWE-190 : Update by YOUNGJUN,CHO
                        if (stringDeptIDArray.length > 0) {
                            
                            String[] longDeptIDArray = new String[stringDeptIDArray.length];
                            System.arraycopy(stringDeptIDArray, 0, longDeptIDArray, 0, stringDeptIDArray.length);
                            LOG.debug("userIDs: {}", userIDs);
                            
                            if (newDoc.getType() == TotDocType.TOT_DOC) {
                                LOG.debug("userIDs: {}", userIDs);
                                new ReportUpdate().deptUserInsert(moumiPm, newDoc, newDocTable, longDeptIDArray);
                            }

                            LOG.debug("board make DEL");
                            
                            kr.co.kihyun.beans.entity.Board board = new kr.co.kihyun.beans.entity.Board(title);
                            board.setUser(mUser);
                            board.setContents(notify);
                            board.setTotDoc(newDoc);
                            board.setCategory(moumiPm.getObjectById(Category.class, Category.ID_TOT_DOC_COMMENT));
                            
                            LOG.debug("DEL ID: {}, GROUP_ID: {}, REP_LEVEL: {}, STEP: {}, TITLE: {}, WRITE_DATE: {}",
                                new Object[] {board.getId(), board.getCategory(), board.getRepLevel(), board.getStep(), board.getTitle(), board.getWriteDate()});

                            FileUtil.delUpFiles(svrFilenames, board);
                            moumiPm.makePersistent(board);
                            tx.commit();

                            /**************** session의 doc info 초기화 ****************/
                            MDoc.initSession(session);

                            if (docGroupID == MDoc.TOT_DOC) {
                                out.println(ServletUtil.getJavaScript("document.location.replace('/totsys/totper/mydocbox/prssbox/doc_list.jsp?docType="+prss+"')"));
                            } else if (docGroupID == MDoc.FORM_DOC) {
                                if(HttpSSOLogin.getSysAuth(req) == MoumiConfig.SYSADM) {
                                    out.println(ServletUtil.redirect("/totsys/sysadm/formbox/doc_list.jsp"));
                                } else {
                                    out.println(ServletUtil.redirect("/totsys/totper/mydocbox/formbox/doc_list.jsp"));
                                }
                            }
                        }
                        //================================================

		} catch (Exception e) {
			e.printStackTrace();
			LOG.error(MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.registrition")+ MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.fail") +" {}, {}", new Object[] {
					usID, req.getRemoteAddr() });
                        //v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN
//			out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc")
//					+ MoumiConfig.getMessageBundle().getString("moumi.message.popup.errorAdmin")));
                        
                        // 수정 : 외부 입력값 필터링
                        String callbackFunc = MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc")
					    + MoumiConfig.getMessageBundle().getString("moumi.message.popup.errorAdmin");
                        String filtered_callbackFunc = callbackFunc.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
                        LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpDelFile.doPost() filtered_callbackFunc={}, Not Test", filtered_callbackFunc);
                        out.println(ServletUtil.getJavaScript(filtered_callbackFunc));
                        //============================================================    
                        
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			moumiPm.close();
			if (eCrossTx.isActive()) {
				eCrossTx.rollback();
			}
			eCrossPm.close();
		}
	}

	private TotTable tableRegist(PersistenceManager pm, int defItemSize, int tableType, String tableTypes, TotDoc newDoc) {
		TotTable totTable = new TotTable(newDoc);
		totTable.setType(TotTable.TotTableType.asType(tableType));
		totTable.setTypes(tableTypes);
		totTable.setItemSize(defItemSize);
		pm.makePersistent(totTable);

		return totTable;
	}

	private TotDoc docRegist(PersistenceManager pm, String docName, ExecutionCode execCode, String handyName,
			MUser mUser, Date stDate, Date edDate,
			AccessAuth accAuth, TotDoc.TotRange totRange, String docForm, TotDoc repDoc,
			int docGroupID, MDept mDept, TotDocAppendType appendType,
			String acceptanceLimitStrategy, Long submitLimit, String prss) {
		LOG.debug("register is: {}", mUser);
		TotDoc newDoc = new TotDoc(docName, mDept, docForm);
		


		newDoc.setUser(mUser);
		newDoc.setExecutionCode(execCode);
		newDoc.setHandyName(handyName);
		newDoc.setStartDate(stDate);
		newDoc.setEndDate(edDate);
		newDoc.setAccessAuth(accAuth);
		newDoc.setTotRange(totRange);
		newDoc.setMasterTotDoc(repDoc);
		newDoc.setType(TotDocType.asDocType(docGroupID));
		newDoc.setRegDate(new Date());
		newDoc.setAppendType(appendType);
		AcceptanceLimitStrategy acptLimitStrategy = AcceptanceLimitStrategy.create(acceptanceLimitStrategy, submitLimit);
		acptLimitStrategy.setProcess(TotDocProcess.valueOf(prss));
		newDoc.setAcceptanceLimitStrategy(acptLimitStrategy);
		pm.makePersistent(newDoc);

		return newDoc;
	}
}
