/***********************************************************************************
 * @@ Program Name : HttpShareDocSet.java
 * @@ Description  : 공유문서의 정보를 관리한다.
 * @@ Author       : KWON,HAN
 * @@ Create Date  : 2014.08.27
 * @@ History      :
 ***********************************************************************************/

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

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.util.List;
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.service.ShareDocService;
import kr.co.kihyun.beans.entity.ShareDoc;
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.doc.HttpShareDocSet")
public class HttpShareDocSet extends HttpServlet {
	private static final Logger LOG = LoggerFactory.getLogger(HttpShareDocSet.class);
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;
        private ResultSet rs = null;

	@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();

            /*********** User HttpLogin check ***********/
            if (!HttpSSOLogin.isLogin(req)) {
                String connURL = "location='/totsys/login/login.jsp';";
                out.println(ServletUtil.getJavaScript(connURL));
                return;
            }
            /********** session내의 userId **********/
	    String usID = HttpSSOLogin.getLoginID(req);   //등록자 ID

            /********** parameter value **********/
//xxx            Long docID = MLong.parseLong(req.getParameter("docID"));
            String docID = MString.checkNull(req.getParameter("docID"));
            String sDocReportType = MString.checkNull(req.getParameter("docReportType"));   //문서 구분(D:집계문서, R:제출문서)
            String userIDs = Encoder.toJava(req.getParameter("userIDs"));
            String types = Encoder.toJava(req.getParameter("types"));
            String exeFlag = Encoder.toJava(req.getParameter("exeFlag"));
            String callbackFunc = Encoder.toJava(req.getParameter("callbackFunc"));


            Long lnShareDocid = null;                  //공유문서 ID
            Boolean blUserExist = false;               //공유자 존재여부

//            System.out.println("HttpShareDocSet.doPost =======================");
//            System.out.println("docID          = "+docID);
//            System.out.println("sDocReportType = "+sDocReportType);
//            System.out.println("userIDs        = "+userIDs);
//            System.out.println("types          = "+types);
//            System.out.println("==============================================");

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

            try {
                tx.begin();

                docID = docID.trim();
                if (docID != null && !"".equals(docID)) {
                    String[] docIDList = docID.split(",");

                    for (int x = 0; x < docIDList.length; x++) {
//                    System.out.println("HttpShareDocSet.doPost==========");
//                    System.out.println("docIDList = " + docIDList[x]);
//                    System.out.println("================================");

                        //++++++++++++++++++++++++++++++++++++++++++++++++++++++
                        //1.문서 ID(DOC_ID), 문서 구분(DOC_REPORT_TYPE)에 해당하는 모든 데이터를 조회한다.
                        ShareDocService shareDocSearch = new ShareDocService(pm);
                        List tmpList  = shareDocSearch.getSearchDocIdType("", docIDList[x], sDocReportType);

                        //2. 1.의 모든 데이터의 삭제여부를 'Y'으로 변경한다.
                        if(tmpList != null) {
                            for(int ii=0; ii<tmpList.size(); ii++) {
                                Object[] objData = (Object[])tmpList.get(ii);
//                                System.out.println("HttpShareDocSet.doPost() tmpList ==========");
//                                System.out.println("ID = " + objData[0]);
//                                System.out.println("USER_ID = " + objData[1]);
//                                System.out.println("==========================================");
                                ShareDoc shareDocDel = pm.getObjectById(ShareDoc.class, ((BigDecimal)objData[0]).longValue());   //0.ID
                                shareDocDel.setDelYn("Y");
                                pm.makePersistent(shareDocDel);
                            }
                        }

                        //3. 공유자 ID 와 1.의 모든 데이터에 대해서 비교하여 공유자ID가
                        //   3.1 존재하면 삭제여부를 'N'으로 변경한다.
                        //   3.2 존재하지 않으면 신규로 생성한다.
                        userIDs = userIDs.trim();
                        if (userIDs != null && !"".equals(userIDs)) {
                            String[] userIDList = userIDs.split(",");

                            for (int i = 0; i < userIDList.length; i++) {
                                lnShareDocid = null;
                                blUserExist = false;

                                if(tmpList != null) {
                                    for(int j=0; j<tmpList.size(); j++) {
                                        Object[] objData = (Object[])tmpList.get(j);

                                        if(userIDList[i].equals(objData[1].toString())) {  //1.USER_ID
                                            lnShareDocid = ((BigDecimal)objData[0]).longValue();              //0.ID
                                            blUserExist = true;
                                        }
                                    }
                                }

                                //3.1.
                                if(blUserExist) {
                                    ShareDoc shareDocUpd = pm.getObjectById(ShareDoc.class,lnShareDocid);

                                    shareDocUpd.setDelYn("N");
                                    shareDocUpd.setRegId(usID);
                                    pm.makePersistent(shareDocUpd);

                                //3.2.
                                } else {
                                    ShareDoc shareDocIns = new ShareDoc();

                                    shareDocIns.setDelYn("N");
                                    shareDocIns.setDocId(MLong.parseLong(docIDList[x]));
                                    shareDocIns.setDocReportType(sDocReportType);
                                    shareDocIns.setRegId(usID);
                                    shareDocIns.setUserId(userIDList[i]);
                                    pm.makePersistent(shareDocIns);
                                }
                            }
                        }
                        //++++++++++++++++++++++++++++++++++++++++++++++++++++++
                    } //for
                } //if


                tx.commit();

                //사용자공유 변경 되었습니다.
                out.println("<script> alert(\""+ MoumiConfig.getMessageBundle().getString("moumi.message.popup.selectShareUserInclude")+"\")</script>");
              //if(sDocReportType != null && "R".equals(sDocReportType)) {
              if(exeFlag != null && "list".equals(exeFlag)) {
                out.println("<script> opener."+callbackFunc+"; </script>");
              }
                out.println("<script> window.close(); </script>");

            } catch (Exception e) {
                //사용자공유 변경 실패! 다시 시도 하여 주세요.
                out.println("<script> alert(\""+ MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.user")+MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.share") + ' ' + MoumiConfig.getMessageBundle().getString("moumi.message.popup.alterFail")+"\")</script>");
                //v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN
//                out.println("<script> window.close(); </script>");

                // 수정 : 외부 입력값 필터링
                String callbackFunc2 = "<script> window.close(); </script>";
                String filtered_callbackFunc2 = callbackFunc2.replaceAll("&","").replaceAll(",","");
                LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpRecogSet.doPost() filtered_callbackFunc2={}, Not Test", filtered_callbackFunc2);
                out.println(filtered_callbackFunc2);
                //========================================

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


