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

import java.io.IOException;
import java.io.PrintWriter;
//import java.util.Calendar;
//import java.util.Date;
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.beans.entity.MUser;
import kr.co.kihyun.beans.entity.Repoadm;
import kr.co.kihyun.beans.entity.TotDoc;
import kr.co.kihyun.beans.entity.TotReport;
import kr.co.kihyun.beans.entity.util.*;
//import kr.co.kihyun.beans.totsys.report.ReportUpdate;
import kr.co.kihyun.beans.totsys.report.ReportUpdate2;
import kr.co.kihyun.beans.user.GroupView;
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.datanucleus.ObjectManager;
import org.datanucleus.jdo.JDOPersistenceManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebServlet("/servlet/kr.co.kihyun.beans.totsys.doc.HttpDeptSet")
public class HttpDeptSet extends HttpServlet {

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

    @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 {
//Date startDate = Calendar.getInstance().getTime();   //test @@@
        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;
        }

        /**
         * ******** parameter value *********
         */
        Long docID = MLong.parseLong(req.getParameter("docID"));
        Long reportID = MLong.parseLong(req.getParameter("reportID"));
        String usedType = MString.checkNull(req.getParameter("usedType"));
        String deptIDs = Encoder.toJava(req.getParameter("deptIDs"));
        String types = Encoder.toJava(req.getParameter("types"));

        TotReport totReport = null;
        TotDoc totDoc = null;

        PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
        Transaction tx = pm.currentTransaction();
        ObjectManager om = ((JDOPersistenceManager) tx.getPersistenceManager()).getObjectManager(); // jeus 6 proplem
        try {
            tx.begin();

            if ("RECOG".equals(usedType)) {
                totReport = pm.getObjectById(TotReport.class, reportID);
                reportUpdate(pm, totDoc, totReport, deptIDs, types, usedType);
            } else {
                totDoc = pm.getObjectById(TotDoc.class, docID);
                reportUpdate(pm, totDoc, totReport, deptIDs, types, usedType);
            }

            if (!"RECOG".equals(usedType)) {
                out.println("<script> alert(\"" + MoumiConfig.getMessageBundle().getString("moumi.message.popup.deptUserSuccess") + "\")</script>");
                out.println("<script> window.close(); </script>");
            } else {
                out.println("<script> alert(\"" + MoumiConfig.getMessageBundle().getString("moumi.message.popup.recogSuccess") + "\")</script>");
                out.println("<script> opener.location.reload(); </script>");
                out.println("<script> window.close(); </script>");
            }

            om.postCommit(); // jeus 6 problem
            tx.commit();
        } catch (Exception e) {
            if (!"RECOG".equals(usedType)) {
                out.println("<script> alert(\"" + MoumiConfig.getMessageBundle().getString("moumi.message.popup.deptUserFail") + "\")</script>");
                out.println("<script> window.close(); </script>");
            } else {
                out.println("<script> alert(\"" + MoumiConfig.getMessageBundle().getString("moumi.message.popup.recogFile") + "\")</script>");
                out.println("<script> window.close(); </script>");
            }
        } finally {
            if (tx.isActive()) {
                tx.rollback();
            }
            pm.close();
//Date endDate = Calendar.getInstance().getTime();    //test @@@
//System.out.println("HttpDeptSet.doPost =========================================");
//System.out.println("startDate = " + startDate);
//System.out.println("endDate = " + endDate);
//System.out.println("============================================================");
        }
    }

    private void reportUpdate(PersistenceManager pm, TotDoc totDoc, TotReport totReport, String deptIDs, String types,
            String usedType) throws Exception {
        if (MString.isNull(deptIDs) && MString.isNull(types)) {
            throw new RuntimeException("deptIDs is null or types is null.");
        }

        /**
         * ************** 부서/사용자 목록 입력 ***************
         */
        String[] deptIDList = deptIDs.split(",");
//        String[] typeList = types.split(",");
        int all = deptIDList.length;

        StringBuilder dts = new StringBuilder();
        StringBuilder uss = new StringBuilder();
        String userIDs = "";

        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]);
//                    }
//                }
//                System.out.println("!1111");
//            } 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]));
//                        }
//                    }
//                    System.out.println("222222");
//                }
//
//                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]));
//                        }
//                    }
//                        System.out.println("333333");
//                }
//
//            } 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();

        // succNum = reportUpdate.deptUpdate(docID, deptIDList);
        String[] stringDeptIDArray = deptIDs.split(",");
//        String[] longDeptIDArray = new String[stringDeptIDArray.length];
//        System.arraycopy(stringDeptIDArray, 0, longDeptIDArray, 0, stringDeptIDArray.length);
        int succNum = 0;

        if (!"RECOG".equals(usedType)) {

            succNum = new ReportUpdate2().deptUserUpdate(pm, totDoc, stringDeptIDArray);
            //succNum = new ReportUpdate2().deptUserMerge(pm, totDoc, longDeptIDArray);
            /* String[] userIDList = userIDs.split(",");
             new ReportUpdate().deptUserUpdate(pm, totDoc, deptIDList, userIDList);*/
//LOG.debug("succNum={}", succNum);

        } else {
            Repoadm repoadm = null;
            List<Repoadm> repoadms = (List<Repoadm>) pm.detachCopyAll(totReport.getRepoadms());
            String[] userIDList = userIDs.split(",");

            if (userIDList != null) {
                for (int i = 0; i < userIDList.length; i++) {
                    MUser user = pm.getObjectById(MUser.class,
                            userIDList[i].substring(0, userIDList[i].indexOf("/")));
                    if (i == 0) {
                        totReport.setCurrentRepoadm(repoadm);
                        if (repoadms != null) {
                            for (int delIndex = 0; delIndex < repoadms.size(); delIndex++) {
                                LOG.debug("deleteID - {}", repoadms.get(delIndex).getId());
                                Repoadm delRepoadm = pm.getObjectById(Repoadm.class, repoadms.get(delIndex).getId());
                                pm.deletePersistent(delRepoadm);
                            }
                        }
                    }
                    repoadm = new Repoadm();
                    repoadm.setRecogUser(user);
                    repoadm.setTotReport(totReport);
                    repoadm.setRecogNum(i);
                    pm.makePersistent(repoadm);
                }
                pm.makePersistent(totReport);
            }
        }
    }
}
