/***********************************************************************************
 * @@ 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.ArrayList;
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.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.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.HttpUserGroup")
public class HttpUserGroup extends HttpServlet {
	private static final Logger LOG = LoggerFactory.getLogger(HttpUserGroup.class);
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException,
			NumberFormatException {

		doPost(req, res);
		return;
	}

	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException,
			NumberFormatException {

		res.setContentType("text/html;charset=UTF-8");
		PrintWriter out = res.getWriter();

		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"));
		String deptTypes = Encoder.toJava(req.getParameter("deptTypes"));
		String[] deptIDList = deptIDs.split(",");
		String[] typeList = deptTypes.split(",");
                String callbackFunc = MString.checkNull(req.getParameter("callbackFunc"));

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

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

				if (new GroupView().getUserDeptDeptID(deptIDList[a]).length() != 0) {
					if (dts.length() == 0) {
						dts = new GroupView().getUserDeptDeptID(deptIDList[a]);
					} else {
						if (!dts.contains(new GroupView().getUserDeptDeptID(deptIDList[a]))) {
							dts = dts + "," + new GroupView().getUserDeptDeptID(deptIDList[a]);
						}
					}
				}
			} else {
				if (dts.length() == 0) {
					dts = deptIDList[a];
				} else {
					if (!dts.contains(deptIDList[a])) {
						dts = dts + "," + deptIDList[a];
					}
				}
			}
		}

		deptIDs = dts;
		userIDs = uss;

		String[] arrayDeptID = null;

		if (deptIDs != null && deptIDs.length() != 0) {
			String[] stringDeptIDList = deptIDs.split(",");
			arrayDeptID = new String[stringDeptIDList.length];
			System.arraycopy(stringDeptIDList, 0, arrayDeptID, 0, stringDeptIDList.length);
		}

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

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

			PersistenceManager pm = new MPersistenceManager(PMF.get().getPersistenceManager());
			Transaction tx = pm.currentTransaction();
			try {
				tx.begin();
				for (int i = 0; i < arrayUserID.length; i++) {
					if (arrayUserID[i].indexOf("/") == -1) {
						arrayUserUserID[i] = arrayUserID[i];
						arrayUserDeptID[i] = pm.getObjectById(MUser.class, arrayUserUserID[i]).getUpperDept(pm).getId();
					} else { // FIXME: Remove me.
						tempArray = arrayUserID[i].split("/");
						arrayUserUserID[i] = tempArray[0];
						arrayUserDeptID[i] = tempArray[1];
					}
				}
				tx.rollback();
			} finally {
				if (tx.isActive())
					tx.rollback();
				pm.close();
			}
		}

		int succNum = 0;
		succNum = userGroup(groupName, userID, arrayDeptID, arrayUserUserID, arrayUserDeptID);

		if (succNum > 0) {
			// out.println(ServletUtil.alert("\""+Moumi.getMessageBundle().getString("moumi.message.tot_doc.registrition")+Moumi.getMessageBundle().getString("moumi.message.tot_doc.complete")+"\""));
                        if( !MString.isNull(callbackFunc) ) {
                            out.println(ServletUtil.getJavaScript(callbackFunc));
                        }
                        out.println(ServletUtil.getJavaScript("self.close();"));

			if (userID.equals("admin")) {
				// out.println(JavaScriptUtil.getJavaScript("location.href='/totsys/login/envsetting/group/admin_group_setup.jsp';"));
                                if( MString.isNull(callbackFunc) ) {
                                    out.println(JavaScriptUtil.getJavaScript("opener.document.location.reload();"));
                                }
                                out.println(JavaScriptUtil.getJavaScript("window.close();"));
			} else {
				// out.println(JavaScriptUtil.getJavaScript("location.href='/totsys/login/envsetting/group/group_setup.jsp';"));
                                if( MString.isNull(callbackFunc) ) {
                                    out.println(JavaScriptUtil.getJavaScript("opener.document.location.reload();"));
                                }
				out.println(JavaScriptUtil.getJavaScript("window.close();"));
			}
		} else {
			out.println(ServletUtil.alert(MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.registrition")+MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.fail")));
			out.println(ServletUtil.getJavaScript("self.close();"));

			if (userID.equals("admin")) {
				// out.println(JavaScriptUtil.getJavaScript("location.href='/totsys/login/envsetting/group/admin_group_setup.jsp';"));
				out.println(JavaScriptUtil.getJavaScript("window.close();"));
			} else {
				// out.println(JavaScriptUtil.getJavaScript("location.href='/totsys/login/envsetting/group/group_setup.jsp';"));
                            
                                //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) : HttpUserGroup.doPost() filtered_callbackFunc={}, Not Test", filtered_callbackFunc2);
                                out.println(JavaScriptUtil.getJavaScript(filtered_callbackFunc2)); 
                                //========================================
                                
			}
		}
	}

	private int userGroup(String groupName, String userID, String[] arrayDeptID,
			String[] arrayUserUserID, String[] arrayUserDeptID) {
		UserPart userPart = null;
		UserDept userDept = null;
		UserUser userUser = null;
		List<UserUser> userUserList = new ArrayList<UserUser>();
		List<UserDept> userDeptList = new ArrayList<UserDept>();

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

			userPart = new UserPart(groupName, pm.getObjectById(MUser.class, userID), "");
			pm.makePersistent(userPart);

			if (arrayDeptID != null) {
				for (int i = 0; i < arrayDeptID.length; i++) {
					userDept = new UserDept(pm.getObjectById(MDept.class, arrayDeptID[i]), pm.getObjectById(
							MDept.class, arrayDeptID[i]).getName(), pm.getObjectById(UserPart.class, userPart.getId()));
					userDeptList.add(userDept);
				}
			}
			if (arrayUserUserID != null) {
				for (int i = 0; i < arrayUserUserID.length; i++) {
					userUser = new UserUser(pm.getObjectById(MUser.class, arrayUserUserID[i]), pm.getObjectById(
							MUser.class, arrayUserUserID[i]).getName(pm), pm.getObjectById(MDept.class,
							arrayUserDeptID[i]), pm.getObjectById(UserPart.class, userPart.getId()));
					userUserList.add(userUser);
				}
			}

			pm.makePersistentAll(userDeptList);
			pm.makePersistentAll(userUserList);

			tx.commit();
			return 1;
		} catch (Exception e) {
			throw new RuntimeException(e);
		} finally {
			if (tx.isActive()) {
				tx.rollback();
			}
			pm.close();
		}
	}
}
