/***********************************************************************************
 * @@ Program Name : HttpFormReader.java Description : 집계문서 폼 정의시 파일 폼 정의, 재사용 폼정의, 복사 폼정의 등으로 분리 해줌 Author : 강원중 Create
 *    Date : 2004.10.13 History :
 * @@
 ***********************************************************************************/

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

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;

import javax.jdo.PersistenceManager;
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.TotDocAppendType;
import kr.co.kihyun.beans.entity.util.*;
import kr.co.kihyun.io.MultipartRequest;
import kr.co.kihyun.lang.MInteger;
import kr.co.kihyun.lang.MLong;
import kr.co.kihyun.lang.MString;
import kr.co.kihyun.lang.StringConverter;
import kr.co.kihyun.moumi.MoumiConfig;
import kr.co.kihyun.moumi.doc.MDoc;
import kr.co.kihyun.moumi.report.MReport;
import kr.co.kihyun.text.html.CallbackHandler;
import kr.co.kihyun.text.html.TagFilter;

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

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

	private String savePath = MoumiConfig.getTotPerTmp().getPath(); // 업로드된 파일의 임시 저장 경로
	private MultipartRequest multi;

	/***************************************************************
	 * attachType=1 : file append form (파일 첨부 폼) doc_fileform_config.jsp attachType=4 : old form (재사용 폼)
	 * doc_oldform_config.jsp attachType=7 : copy form (word 에서 copy form); doc_copyform_config.jsp
	 ****************************************************************/
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		doPost(req, res);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
		PrintWriter out = response.getWriter();
		HttpSession session = request.getSession(true);

		try {
			multi = new MultipartRequest(request, savePath);

			TotDocAppendType appendType = TotDocAppendType.valueOf(MString.checkNull(multi.getParameter("appendType"),
			TotDocAppendType.COPY.toString())); // 파일첨부, 복사, 양식 재사용
			String docName = URLEncoder.encode(MString.checkNull(multi.getParameter("docName")), "UTF-8");
			String execNum = MString.checkNull(multi.getParameter("execNum"));
			String execDate = MString.checkNull(multi.getParameter("execDate"));
			String accAuth = MString.checkNull(multi.getParameter("accAuth"));
			String deptIDs = MString.checkNull(multi.getParameter("deptIDs"));
			String deptNames = URLEncoder.encode(MString.checkNull(multi.getParameter("deptNames")), "UTF-8");
			String deptTypes = MString.checkNull(multi.getParameter("deptTypes"));
			String deptCount = MString.checkNull(multi.getParameter("deptCount"));
			String handyName = MString.checkNull(multi.getParameter("handyName"));
			String totRange = MString.checkNull(multi.getParameter("totRange"));
			String userIDs = MString.checkNull(multi.getParameter("userIDs"));
			String userNames = URLEncoder.encode(MString.checkNull(multi.getParameter("userNames")), "UTF-8");
			String userCount = MString.checkNull(multi.getParameter("userCount"));
			Long reuseDocID = MLong.parseLong(multi.getParameter("reuseDocID"), null);
			// String repDocID = multi.getParameter("repDocID");
			int docGroupID = MInteger.parseInt(multi.getParameter("docGroupID"));
			String isFromFormBox = MString.checkNull(multi.getParameter("isFromFormBox"));
			String docForm;
			int fileCount = MInteger.parseInt(multi.getParameter("fileCount"));
			// String usrFilenames = Encoder.toJava(multi.getParameter("usrFilenames"));
			// String svrFilenames = Encoder.toJava(multi.getParameter("svrFilenames"));
			String usrFilenames = URLEncoder.encode(MString.checkNull(multi.getParameter("usrFilenames")), "UTF-8");
			String svrFilenames = URLEncoder.encode(MString.checkNull(multi.getParameter("svrFilenames")), "UTF-8");
			String fileInfoList = MString.checkNull(multi.getParameter("fileInfos"));


			String title = docName + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.input") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.trick") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.and") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.relation") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.doc");
			title = TagFilter.convertMeta(title);
			String notify = MString.checkNull(multi.getParameter("notify"));

			if (!MString.isNull(notify)) {
				notify = CallbackHandler.getCutPreTag(notify);
				notify = TagFilter.convertSingle(notify);
				session.setAttribute("notify", notify);
			}else if(fileCount >= 1){
				session.setAttribute("notify", "[ 첨부파일을 참고하여 작성바랍니다 ] \n");
			}

			if (!MString.isNull((String) session.getAttribute("notify"))) {
				notify = (String) session.getAttribute("notify");
			}

			System.out.println("filecount " + fileCount + " fileInfoList " + fileInfoList + " usrFilenames " +usrFilenames +" title " + title + " notify " +notify );
			/******************** 새로 추가 된 부분 ********************/
			String tableDefines = MString.checkNull(multi.getParameter("tableDefines"));
			String itemNames = URLEncoder.encode(MString.checkNull(multi.getParameter("itemNames")), "UTF-8");
			String tableNums = URLEncoder.encode(MString.checkNull(multi.getParameter("tableNums")), "UTF-8");
			String colNums = URLEncoder.encode(MString.checkNull(multi.getParameter("colNums")), "UTF-8");
			String rowNums = URLEncoder.encode(MString.checkNull(multi.getParameter("rowNums")), "UTF-8");
			String itemSizes = URLEncoder.encode(MString.checkNull(multi.getParameter("itemSizes")), "UTF-8");
			String itemDescs = URLEncoder.encode(MString.checkNull(multi.getParameter("itemDescs")), "UTF-8");

			String itemExprs = URLEncoder.encode(MString.checkNull(multi.getParameter("itemExprs")), "UTF-8");
			String itemTypes = URLEncoder.encode(MString.checkNull(multi.getParameter("itemTypes")), "UTF-8");
			String backDash = MString.checkNull(multi.getParameter("backDash"));
			String sessionForm = null;
			boolean check = true;

			String action = "/totsys/totper/mydocbox/regbox/doc_form_config.jsp";
			if (docGroupID == MDoc.FORM_DOC)
				action = "/totsys/totper/mydocbox/formbox/doc_form_config.jsp";

//			if (appendType == TotDocAppendType.COPY || appendType == TotDocAppendType.FILE || appendType == TotDocAppendType.SYSTEM) {
				// form 복사
				docForm = multi.getParameter("copyForm");
				docForm = docForm.replaceAll("\"DataInput\"",
						"<table width=700 border=0><tr><td width='100%'></td></tr></table>");
				docForm = CallbackHandler.getCutPreTag(docForm);
				docForm = StringConverter.toOneLine(TagFilter.convertSingle(docForm));

                                // 2014.10.17 By YoungJun Cho. (사용자가 입력한 테이블표에서 불필요한 태그 또는 요소들을 제거한다.)
                                docForm = TagFilter.removeGarbageElements(docForm);

				if ((String) session.getAttribute("docForm") == "" || (String) session.getAttribute("docForm") == null) {
					check = true;
				} else {
					sessionForm = (String) session.getAttribute("docForm");
					check = MReport.geteExtractTable(docForm, sessionForm);
				}

				session.setAttribute("docForm", docForm);

				StringBuilder strbuf = new StringBuilder();
				strbuf.append("<html>");
				strbuf.append("<body topmargin=0 leftmargin=0 onload=\"document.copyform.submit();\">\n");
				strbuf.append("<form name='copyform' method='POST' action='");
				strbuf.append(action);
				strbuf.append("'>\n");
				strbuf.append("		<input type=hidden name =\"docName\" value=\"");
				strbuf.append(docName);
				strbuf.append("\">\n");
				strbuf.append("		<input type=hidden name =\"execNum\" value=\"");
				strbuf.append(execNum);
				strbuf.append("\">\n");
				strbuf.append("		<input type=hidden name =\"execDate\" value=\"");
				strbuf.append(execDate);
				strbuf.append("\">\n");
				strbuf.append("		<input type=hidden name =\"appendType\" value=\"");
				strbuf.append(appendType);
				strbuf.append("\">\n");
				strbuf.append("		<input type=hidden name =\"accAuth\" value=\"");
				strbuf.append(accAuth);
				strbuf.append("\">\n");
				strbuf.append("		<input type=hidden name =\"deptIDs\" value=\"");
				strbuf.append(deptIDs);
				strbuf.append("\">\n");
				strbuf.append("		<input type=hidden name =\"deptNames\" value=\"");
				strbuf.append(deptNames);
				strbuf.append("\">\n");
				strbuf.append("		<input type=hidden name =\"deptTypes\" value=\"");
				strbuf.append(deptTypes);
				strbuf.append("\">\n");
				strbuf.append("		<input type=hidden name =\"deptCount\" value=\"");
				strbuf.append(deptCount);
				strbuf.append("\">\n");
				strbuf.append("		<input type=hidden name =\"userIDs\" value=\"");
				strbuf.append(userIDs);
				strbuf.append("\">\n");
				strbuf.append("		<input type=hidden name =\"userNames\" value=\"");
				strbuf.append(userNames);
				strbuf.append("\">\n");
				strbuf.append("		<input type=hidden name =\"userCount\" value=\"");
				strbuf.append(userCount);
				strbuf.append("\">\n");
				strbuf.append("		<input type=hidden name =\"docGroupID\" value=\"");
				strbuf.append(docGroupID);
				strbuf.append("\">\n");

				strbuf.append("         <input type=hidden name =\"handyName\" value=\"");
				strbuf.append(handyName);
				strbuf.append("\">\n");

				strbuf.append("         <input type=hidden name =\"totRange\" value=\"");
				strbuf.append(totRange);
				strbuf.append("\">\n");

				strbuf.append("		<input type=hidden name =\"isFromFormBox\" value=\"");
				strbuf.append(isFromFormBox);
				strbuf.append("\">\n");
				strbuf.append("		<input type=hidden name =\"title\" value=\"");
				strbuf.append(title);
				strbuf.append("\">\n");
				strbuf.append("		<input type=hidden name =\"fileCount\" value=\"");
				strbuf.append(fileCount);
				strbuf.append("\">\n");
				strbuf.append("		<input type=hidden name =\"usrFilenames\" value=\"");
				strbuf.append(usrFilenames);
				strbuf.append("\">\n");
				strbuf.append("		<input type=hidden name =\"svrFilenames\" value=\"");
				strbuf.append(svrFilenames);
				strbuf.append("\">\n");
				strbuf.append("		<input type=hidden name =\"fileInfoList\" value=\"");
				strbuf.append(fileInfoList);
				strbuf.append("\">\n");
				strbuf.append("		<input type=hidden name =\"java\" value=\"1\">\n");

				if (check == true) {
					/**************************************************************************/
					//strbuf.append("\">\n");
					strbuf.append("		<input type=hidden name =\"backDash\" value=\"");
					strbuf.append(backDash);
					strbuf.append("\">\n");
					strbuf.append("		<input type=hidden name =\"tableDefines\" value=\"");
					strbuf.append(tableDefines);
					strbuf.append("\">\n");
					strbuf.append("		<input type=hidden name =\"itemNames\" value=\"");
					strbuf.append(itemNames);
					strbuf.append("\">\n");
					strbuf.append("		<input type=hidden name =\"tableNums\" value=\"");
					strbuf.append(tableNums);
					strbuf.append("\">\n");
					strbuf.append("		<input type=hidden name =\"colNums\" value=\"");
					strbuf.append(colNums);
					strbuf.append("\">\n");
					strbuf.append("		<input type=hidden name =\"rowNums\" value=\"");
					strbuf.append(rowNums);
					strbuf.append("\">\n");
					strbuf.append("		<input type=hidden name =\"itemSizes\" value=\"");
					strbuf.append(itemSizes);
					strbuf.append("\">\n");
					strbuf.append("		<input type=hidden name =\"itemDescs\" value=\"");
					strbuf.append(itemDescs);
					strbuf.append("\">\n");
					strbuf.append("		<input type=hidden name =\"itemExprs\" value=\"");
					strbuf.append(itemExprs);
					strbuf.append("\">\n");
					strbuf.append("		<input type=hidden name =\"itemTypes\" value=\"");
					strbuf.append(itemTypes);
					strbuf.append("\">\n");
					/**************************************************************************/
				}

				strbuf.append("</form>\n");
				strbuf.append("</body>\n");
				strbuf.append("</html>");
				out.println(strbuf.toString());
				return;
//			} else if (appendType == TotDocAppendType.REUSE) {
//				// form 재사용
//				if (reuseDocID != null) {
//
//					PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
//					try {
//						TotDoc doc = pm.getObjectById(TotDoc.class, reuseDocID);
//						docForm = doc.getForm();
//					} finally {
//						pm.close();
//					}
//				} else {
//
//					docForm = multi.getParameter("copyForm");
//				}
//
//                                // 2014.10.17 By YoungJun Cho. (사용자가 입력한 테이블표에서 불필요한 태그 또는 요소들을 제거한다.)
//                                docForm = TagFilter.removeGarbageElements(docForm);
//
//				docForm = docForm.replaceAll("Moumi.getMessageBundle().getString(\"moumi.message.tot_doc.inputWindow\")",
//						"<table width=700 border=0><tr><td width='100%'></td></tr></table>");
//
//				docForm = CallbackHandler.getCutPreTag(docForm);
//				session.setAttribute("docForm", docForm);
//				StringBuilder strbuf = new StringBuilder();
//				strbuf.append("<html>");
//				strbuf.append("	<body topmargin=0 leftmargin=0 onload=\"document.oldform.submit();\">\n");
//				strbuf.append("<form name='oldform' method='POST' action='" + action + "'>\n");
//				strbuf.append("		<input type=hidden name =\"docName\" value=\"");
//				strbuf.append(docName);
//				strbuf.append("\">\n");
//				strbuf.append("		<input type=hidden name =\"execNum\" value=\"");
//				strbuf.append(execNum);
//				strbuf.append("\">\n");
//				strbuf.append("		<input type=hidden name =\"execDate\" value=\"");
//				strbuf.append(execDate);
//				strbuf.append("\">\n");
//				strbuf.append("		<input type=hidden name =\"appendType\" value=\"");
//				strbuf.append(appendType);
//				strbuf.append("\">\n");
//				strbuf.append("		<input type=hidden name =\"accAuth\" value=\"");
//				strbuf.append(accAuth);
//				strbuf.append("\">\n");
//				strbuf.append("		<input type=hidden name =\"deptIDs\" value=\"");
//				strbuf.append(deptIDs);
//				strbuf.append("\">\n");
//				strbuf.append("		<input type=hidden name =\"deptNames\" value=\"");
//				strbuf.append(deptNames);
//				strbuf.append("\">\n");
//				strbuf.append("		<input type=hidden name =\"deptTypes\" value=\"");
//				strbuf.append(deptTypes);
//				strbuf.append("\">\n");
//				strbuf.append("		<input type=hidden name =\"deptCount\" value=\"");
//				strbuf.append(deptCount);
//				strbuf.append("\">\n");
//				strbuf.append("		<input type=hidden name =\"userIDs\" value=\"");
//				strbuf.append(userIDs);
//				strbuf.append("\">\n");
//				strbuf.append("		<input type=hidden name =\"userNames\" value=\"");
//				strbuf.append(userNames);
//				strbuf.append("\">\n");
//				strbuf.append("		<input type=hidden name =\"userCount\" value=\"");
//				strbuf.append(userCount);
//				strbuf.append("\">\n");
//				strbuf.append("		<input type=hidden name =\"docGroupID\" value=\"");
//				strbuf.append(docGroupID);
//				strbuf.append("\">\n");
//				strbuf.append("		<input type=hidden name =\"isFromFormBox\" value=\"");
//				strbuf.append(isFromFormBox);
//				strbuf.append("\">\n");
//				strbuf.append("		<input type=hidden name =\"title\" value=\"");
//				strbuf.append(title);
//				strbuf.append("\">\n");
//				strbuf.append("		<input type=hidden name =\"fileCount\" value=\"");
//				strbuf.append(fileCount);
//				strbuf.append("\">\n");
//				strbuf.append("		<input type=hidden name =\"usrFilenames\" value=\"");
//				strbuf.append(usrFilenames);
//				strbuf.append("\">\n");
//				strbuf.append("		<input type=hidden name =\"svrFilenames\" value=\"");
//				strbuf.append(svrFilenames);
//				strbuf.append("\">\n");
//				strbuf.append("		<input type=hidden name =\"fileInfoList\" value=\"");
//				strbuf.append(fileInfoList);
//				strbuf.append("\">\n");
//				strbuf.append("		<input type=hidden name =\"notify\" value=\"");
//				strbuf.append(notify);
//				strbuf.append("\">\n");
//				strbuf.append("		<input type=hidden name =\"reuseDocID\" value=\"");
//				strbuf.append(reuseDocID);
//				strbuf.append("\">\n");
//
//				strbuf.append("         <input type=hidden name =\"handyName\" value=\"");
//				strbuf.append(handyName);
//				strbuf.append("\">\n");
//
//				strbuf.append("         <input type=hidden name =\"totRange\" value=\"");
//				strbuf.append(totRange);
//				strbuf.append("\">\n");
//
//				strbuf.append("		<input type=hidden name =\"java\" value=\"1\">\n");
//				strbuf.append("		</form>\n");
//				strbuf.append("	</body>\n");
//				strbuf.append("</html>\n");
//				out.println(strbuf.toString());
//
//				return;
//			}
                //44.적절하지 않은 예외처리(광범위예외클래스)_CWE-754 Add by YOUNGJUN,CHO
                } catch (IOException ioex) {
                        ioex.printStackTrace();
                //++++++++++++++++++++++++++++++++++++++++++++++++
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}
}
