/***********************************************************************************
 * @@ Program Name : HttpUserGroup.java Description : 기관에속한 부서들의 목록 Author : Create Date : History :
 * @@
 ***********************************************************************************/

package kr.co.kihyun.beans.user;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
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.MDept;
import kr.co.kihyun.beans.entity.MUser;
import kr.co.kihyun.beans.entity.UserDept;
import kr.co.kihyun.beans.entity.UserPart;
import kr.co.kihyun.beans.entity.UserUser;
import kr.co.kihyun.beans.entity.util.*;
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 kr.co.kihyun.text.javascript.JavaScriptUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebServlet("/servlet/kr.co.kihyun.beans.user.HttpUserGroupModify")
public class HttpUserGroupModify extends HttpServlet {
        private static final Logger LOG = LoggerFactory.getLogger(HttpUserGroup.class);
	/**
	 *
	 */
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException,
			NumberFormatException {
		doPost(req, res);
		return;
	}

	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException,
			NumberFormatException {
		res.setContentType("text/html;charset=UTF-8");
		PrintWriter out = res.getWriter();
		out.print("<script>if(!opener)opener=parent;</script>");
		String groupName = Encoder.toJava(req.getParameter("groupName"));
		String deptIDs = Encoder.toJava(req.getParameter("deptIDs"));
		String userIDs = Encoder.toJava(req.getParameter("userIDs"));
		String userID = Encoder.toJava(req.getParameter("userID"));
		//Long partID = MLong.parseLong(req.getParameter("partID"), 0L);
                String partID = Encoder.toJava(req.getParameter("partID"));
		String deptTypes = Encoder.toJava(req.getParameter("deptTypes"));
		String valid = Encoder.toJava(req.getParameter("valid"));
                String callbackFunc = MString.checkNull(req.getParameter("callbackFunc"));
		String userValid = "";
		int sysAuth = HttpSSOLogin.getSysAuth(req);

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

			UserPart userPart = pm.getObjectById(UserPart.class, partID);
			UserDept userDept = null;
			UserUser userUser = null;
			MDept mDept = null;
			MUser mUser = null;

			if (sysAuth == MoumiConfig.TOTPER && !HttpSSOLogin.getLoginID(req).equals(userPart.getUser(pm).getId())) {
				out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.notModifyGroup")));
				out.println(ServletUtil.getJavaScript("self.close();"));
				return;
			}

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

			int all = typeList.length;
			String dts = "";
			String uss = "";
			String usvalid = "";
			String dtvalid = "";

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

					if (new GroupView().getUserDeptDeptID(deptIDList[a]) != "") {
						if (dts.equals("")) {
							dts = new GroupView().getUserDeptDeptID(deptIDList[a]);
							dtvalid = validList[a].substring(0, 1);
						} else {
							if (!dts.contains(new GroupView().getUserDeptDeptID(deptIDList[a]))) {
								dts = dts + "," + new GroupView().getUserDeptDeptID(deptIDList[a]);
								dtvalid = dtvalid + "," + validList[a].substring(0, 1);
							}
						}
					}
				} else {
					if (dts.equals("")) {
						dts = deptIDList[a];
						dtvalid = validList[a].substring(0, 1);
					} else {
						if (!dts.contains(deptIDList[a])) {
							dts = dts + "," + deptIDList[a];
							dtvalid = dtvalid + "," + validList[a].substring(0, 1);
						}
					}
				}
			}

			deptIDs = dts;
			userIDs = uss;
			userValid = usvalid;

			Long[] arrayDeptID = null;
			String[] arrayUserValidString = userValid.split(",");
			boolean[] arrayUserValid = new boolean[arrayUserValidString.length];
			for (int i = 0; i < arrayUserValidString.length; i++) {
				arrayUserValid[i] = "1".equals(arrayUserValidString);
			}

			//if (deptIDs != null && !deptIDs.equals("")) {
				String[] stringDeptIDList = deptIDs.split(",");
			//	arrayDeptID = new Long[stringDeptIDList.length];
			//	for (int i = 0; i < stringDeptIDList.length; i++)
			//		arrayDeptID[i] = MLong.parseLong(stringDeptIDList[i], 0L);
			//}

			String[] arrayUserID = null;
			String[] arrayUserUserID = null;
			Long[] arrayUserDeptID = null;
			String[] tempArray = null;

			if (userIDs != null && !userIDs.equals("")) {
				arrayUserID = userIDs.split(",");
				arrayUserUserID = new String[arrayUserID.length];
				arrayUserDeptID = new Long[arrayUserID.length];

				for (int i = 0; i < arrayUserID.length; i++) {
					tempArray = arrayUserID[i].split("/");
					arrayUserUserID[i] = tempArray[0];
					arrayUserDeptID[i] = MLong.parseLong(tempArray[1], 0L);
				}
			}

			userPart.setName(groupName);
                        userPart.setModDate(new Date());
			pm.makePersistent(userPart);

			if (userPart.getUserDepts() != null){
				pm.deletePersistentAll(userPart.getUserDepts());
                        }
			if (userPart.getUserUsers() != null){
				pm.deletePersistentAll(userPart.getUserUsers());
                        }

			//if (arrayDeptID != null) {
			//	for (int i = 0; i < arrayDeptID.length; i++) {
			//		mDept = pm.getObjectById(MDept.class, arrayDeptID[i]);
                        if (deptIDs != null) {
				for (int i = 0; i < stringDeptIDList.length; i++) {

					mDept = pm.getObjectById(MDept.class, stringDeptIDList[i]);
					userDept = new UserDept(mDept, mDept.getName(), userPart);
					pm.makePersistent(userDept);
				}
			}
			if (arrayUserUserID != null) {
				for (int i = 0; i < arrayUserUserID.length; i++) {
					mUser = pm.getObjectById(MUser.class, arrayUserUserID[i]);
					userUser = new UserUser(mUser, mUser.getName(pm), mUser.getUpperDept(pm), userPart);
					pm.makePersistent(userUser);
				}
			}
			tx.commit();

                        out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.userPartSuccess")));
			if( MString.isNull(callbackFunc) ) {
                            out.println(JavaScriptUtil.getJavaScript("opener.document.location.reload();"));
                        }else{
                            out.println(ServletUtil.getJavaScript(callbackFunc));
                        }
                        //out.println(JavaScriptUtil.getJavaScript("opener.location.reload();"));
            out.println(ServletUtil.getJavaScript("self.close();"));
			out.println(JavaScriptUtil.getJavaScript("window.close();"));
		} catch (Exception e) {
			e.printStackTrace();
			out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.popup.groupModifyFail")));
			out.println(ServletUtil.getJavaScript("self.close();"));

                        //v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN
//			out.println(JavaScriptUtil.getJavaScript("window.close();"));

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

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