/*************************************************************************************************
 * 프로그램명 : DocView.java 프로그램설명 : 집계자가 올린 프로젝트 리스트 작성자 : 강원중 작성일 : 2004.01.09 변경일 : 2003.11.30
 **************************************************************************************************/

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

import java.io.IOException;
import java.io.PrintWriter;
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.entity.TotDoc;
import kr.co.kihyun.beans.entity.TotDocType;
import kr.co.kihyun.beans.entity.TotItem;
//import kr.co.kihyun.beans.entity.TotItemType;
import kr.co.kihyun.beans.entity.TotReport;
import kr.co.kihyun.beans.entity.TotReportProcess;
import kr.co.kihyun.beans.entity.TotTable;
import kr.co.kihyun.beans.entity.util.MPersistenceManager;
import kr.co.kihyun.beans.entity.util.*;
//import kr.co.kihyun.beans.totsys.doc.table.item.Item;
//import kr.co.kihyun.beans.totsys.report.ReportUpdate;
import kr.co.kihyun.beans.user.HttpSSOLogin;
import kr.co.kihyun.lang.Encoder;
import kr.co.kihyun.lang.MInteger;
import kr.co.kihyun.lang.MString;
import kr.co.kihyun.moumi.MoumiConfig;
import kr.co.kihyun.moumi.doc.table.MTableRemaker;
import kr.co.kihyun.moumi.doc.table.item.MItemInfo;
//import kr.co.kihyun.moumi.report.MReport;
import kr.co.kihyun.text.html.ServletUtil;

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

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

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

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

		/********** session내의 userId **********/
		String usID = HttpSSOLogin.getLoginID(req);

		/********** parameter value **********/
		Long docID = new Long(MInteger.parseInt(req.getParameter("docID")));
		int tableType = MInteger.parseInt(req.getParameter("tableType"));
		String itemNames = Encoder.toJava(req.getParameter("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"));
		int defItemSize = MInteger.parseInt(req.getParameter("defItemSize"), 10);
		String docForm = (String) session.getAttribute("docForm");
		String tableTypes = MString.checkNull(req.getParameter("tableTypes")); // 새버전 동적/정적 선택# 2008.03.18 구경모
//		int[] tableNumList = null;
//		int[] numList = null;
//		String[] nameList = null;
//		String[] desList = null;
//		int[] sizeList = null;
//		String[] exprList = null;
//		int[] typeList = null;
//		int[] colNumList = null;
//		int[] rowNumList = null;
		int succNum = 0;

		PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
		Transaction tx = pm.currentTransaction();
		try {
			tx.begin();
			// item info value set
			MItemInfo itemInfo = new MItemInfo();
			itemInfo.itemInfo(itemNames, itemSizes, itemExprs, itemDescs, itemTypes, tableNums, colNums, rowNums,
					defItemSize);

			// 셀정의 수식을 엑셀 수식으로 변환하여 form에 적용 시킴
			docForm = MTableRemaker.remake(docForm, itemInfo); // 셀정의 수식을 엑셀저장시 적용되게 해줌
			String targetURI = "";

			TotDoc totDoc = pm.getObjectById(TotDoc.class, docID);
			TotItem totItem = null;
			totDoc.setForm(docForm);
			pm.makePersistent(totDoc);
			pm.deletePersistentAll(totDoc.getTotItems().toArray());
			pm.makePersistentAll(itemInfo.toTotItemList(totDoc));
			// table info value modify
			TotTable totTable = new TotTable(totDoc);
			totTable.setNum(1);
			totTable.setType(TotTable.TotTableType.asType(tableType));
			totTable.setTypes(tableTypes);
			totTable.setItemSize(defItemSize);
			pm.makePersistent(totTable);

			Set<TotReport> reports = totDoc.getTotReports();
			for (TotReport report : reports) {
				report.setProcess(TotReportProcess.ACCEPT);
			}
			pm.makePersistentAll(reports.toArray()); // 모든 totReport process를 접수로 변경
			tx.commit();

			LOG.info(TotDocType.FORM_DOC + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.modify") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.success") +" {}, {}, {}", new Object[] { usID, req.getRemoteAddr(), docID });
			out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.formChangeSuccess")));
			targetURI = (String) session.getAttribute("modifySuccTargetURI") + "&regSuccNum=" + succNum;
			out.println(ServletUtil.redirect(targetURI));
		} catch (Exception e) {
			tx.rollback();
			e.printStackTrace();
			LOG.error(TotDocType.FORM_DOC + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.modify")+ MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.fail") +" {}, {}, {}", new Object[] { usID, req.getRemoteAddr(), docID });
			out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.alterFail")));
                        //v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN
//			out.println(ServletUtil.getJavaScript("history.back();"));
                        
                        // 수정 : 외부 입력값 필터링
                        String callbackFunc = "history.back();";
                        String filtered_callbackFunc = callbackFunc.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
                        LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpDocFormModifyer.doPost() filtered_callbackFunc={}, Not Test", filtered_callbackFunc);
                        out.println(ServletUtil.getJavaScript(filtered_callbackFunc));
                        //============================================================ 
                        
		} finally {
			if (tx.isActive())
				tx.rollback();
			pm.close();
		}
	}
}
