/***********************************************************************************
 * @@ Program Name : HttpDeptList.java Description : 기관에속한 부서들의 목록 Author : 강원중 Create Date : 2003-12-16 History :
 * @@
 ***********************************************************************************/

package kr.co.kihyun.beans.user;

import java.io.IOException;
import java.io.PrintWriter;

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.moumi.MoumiConfig;
import kr.co.kihyun.lang.Encoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebServlet("/servlet/kr.co.kihyun.beans.user.HttpUserList")
public class HttpUserList 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();

		String deptID = null;
		String didList = "";
		String nameList = "";
		String idList = "";
		String selectType = "";

		nameList = Encoder.toJava(req.getParameter("nameList"));
		idList = Encoder.toJava(req.getParameter("idList"));
		selectType = req.getParameter("selectType");

		didList = Encoder.toJava(req.getParameter("didList"));
		deptID = req.getParameter("id");

		if (selectType.equals("right")) { // 추가 타입으로 왔다면
			out.println(getRightList(deptID)); // 부서코드로 인자를 받아 getRigtList() 실행
		} else if (selectType.equals("user")) {
                        //v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN
//			out.println(getUserCheckList(nameList, idList, didList));
                        
                        // 수정 : 외부 입력값 필터링
                        String filtered_nameList = nameList.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
                        String filtered_idList = idList.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
                        String filtered_didList = didList.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
                        LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpUserList.doPost() filtered_nameList={}, Not Test", filtered_nameList);
                        LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpUserList.doPost() filtered_idList={}, Not Test", filtered_idList);
                        LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpUserList.doPost() filtered_didList={}, Not Test", filtered_didList);
                        out.println(getUserCheckList(filtered_nameList, filtered_idList, filtered_didList));    
                        //========================================                        
		}
	}

	private String getRightList(String id) { // 부서코드를 받아서 rightFrame에 개인사용자들을 출력한다.
		StringBuffer strbuf = new StringBuffer();

		Dept dept = new Dept();
		User user = new User();

		String[] arrayID = null; // 사용자들 원본을 받을때 쓰는 변수
		String[] arrayName = null; // 사용자들을 잘라서 넣을때 쓰는 변수

		arrayID = dept.getMultiUserList(id); // 선택되어진 부서의 사용자들을 받는다.

		int count = 0;

		if (arrayID.length > 0) { // 사용자들이 있다면
			count = arrayID.length; // 선택되어진 기관의 부서들의 갯수를 받아온다.

			arrayName = new String[count];
			for (int i = 0; i < count; i++) {
				String[] tmp = arrayID[i].split("/"); // 사용자들을 "/"로 자른다.(/ 뒤에는 이름이 있음)
				// arrayName[i]=user.getName(arrayID[i]);
				arrayName[i] = dept.getName(tmp[1]) + "-" + user.getName(tmp[0]);
			} // 기관명 //사용자명
		} else { // 사용자가 없다면 아무것도 실행 안함
					// throw new NullPointerException();
		}

		/******************** Right Frame(추가 리스트) JavaScript 생성 ********************/
		strbuf.append("<script language=\"javascript\">\n\n");
		strbuf.append("	var seluid='';\n\n");
		strbuf.append("	var seluname='';\n\n");

		strbuf.append("	function movelist(){\n");
		strbuf.append("		if(!(seluid == '' && seluname == '')){\n");
		strbuf.append("			parent.userFrameAdd(seluname+',', seluid+',');\n");
		strbuf.append("		}\n");
		strbuf.append("	}\n\n");

		strbuf.append("	function Select(id,name) {\n");
		strbuf.append("			seluname = name;\n");
		strbuf.append("			seluid = id;\n");
		strbuf.append("	}\n\n");
		strbuf.append("</script>\n");

		/******************** HTML 생성 ********************/
		strbuf.append("<html>\n");
		strbuf.append("	<head></head>\n");
		strbuf.append("<link rel='StyleSheet' href='/totsys/common/css/dtree.css' type='text/css' />\n");
		strbuf.append("<script type='text/javascript' src='/totsys/common/js/dtree.js'></script>\n\n");
		strbuf.append("	<body bgcolor=\"#FFFFFF\" text=\"#000000\" leftmargin=\"0\" topmargin=\"0\" marginwidth=\"0\" marginheight=\"0\">\n");
		strbuf.append("		<form name=AddrList method=Post>\n");
		strbuf.append("		<table border=0 cellpadding=5 cellspacing=2 width=100%>\n");
		strbuf.append("			<tr>\n");
		strbuf.append("				<td>\n");
		strbuf.append("<div class='dtree'>\n");
		strbuf.append("	<script type='text/javascript'>\n");
		strbuf.append("		d = new dTree('d');\n");

		if (count > 0) {
			strbuf.append("		d.add(0,-1,'" + (arrayName[0].split("-"))[0] + "');\n");
		}
		for (int i = 0; i < count; i++) {
			strbuf.append("		d.add('" + arrayID[i] + "',0,\""
					+ (arrayName[i].split("-"))[arrayName[i].split("-").length - 1] + "\",\"javascript: Select('"
					+ arrayID[i] + "','" + arrayName[i] + "');\");\n");
		}

		strbuf.append("		document.write(d);\n");
		strbuf.append("		d.openAll();\n\n");

		strbuf.append("		//-->\n");
		strbuf.append("	</script>\n");

		strbuf.append("</div>\n");

		strbuf.append("				</td>\n");
		strbuf.append("			</tr>\n");
		strbuf.append("		</table>\n");
		strbuf.append("		</form>\n");
		strbuf.append("	</body>\n");
		strbuf.append("</html>\n");

		return strbuf.toString();
	}

	private String getUserCheckList(String name, String id, String did) {
		StringBuffer strbuf = new StringBuffer();

		String[] arrayName = name.split(",");// 선택된사용자 이름 리스트
		String[] arrayID = id.split(","); // 선택된사용자 아이디 리스트
		String[] arrayDID = did.split(","); // 선택된부서 아이디 리스트

		String[] arrayUID;

		int count = 0;
		int dcount = 0;
		int change = 0;
		name = null;

		Dept dept = new Dept();
		User user = new User();

		if (arrayID.length > 0) {

			count = arrayID.length;
			dcount = arrayDID.length;

			if (id.equals(""))
				count = 0;

			if (count != 0) {
				arrayUID = new String[count];

				int isEquals = 0;
				int newSize = 0;

				for (int i = 0; i < count; i++) {
					isEquals = 0;
					for (int j = 0; j < dcount; j++) {
						String[] tmp = arrayID[i].split("/");
						// if((user.getDept(arrayID[i])).equals(arrayDID[j])){ //선택된 사용자의 부서와 선택된 부서 중 같은게 있는지 검사
						if (tmp[1].equals(arrayDID[j])) { // 선택된 사용자의 부서와 선택된 부서 중 같은게 있는지 검사
							isEquals = 1;
							change = 1;
							break;
						}
					}

					if (isEquals == 0) {
						arrayUID[newSize] = arrayID[i];
						newSize = newSize + 1;
					}
				}

				if (newSize == 0) {
					arrayID = new String[1];
					arrayID[0] = "";
					count = 0;
				} else {
					arrayID = new String[newSize];
					for (int a = 0; a < newSize; a++)
						arrayID[a] = arrayUID[a];
					count = newSize;
				}
			}

			if (count == 0) {
				id = "";
				name = "";
			} else {
				String[] tmp = arrayID[0].split("/");
				id = arrayID[0];
				name = dept.getName(tmp[1]) + "-" + user.getName(tmp[0]);
				for (int i = 1; i < count; i++) {
					tmp = arrayID[i].split("/");
					id = id + "," + arrayID[i];
					name = name + "," + dept.getName(tmp[1]) + "-" + user.getName(tmp[0]);
				}
			}
		} else {
			throw new NullPointerException();
		}

		/******************** userFrame(추가 리스트) JavaScript 생성 ********************/
		strbuf.append("<script language=\"javascript\">\n\n");
		if (change == 1) {
			strbuf.append("	alert(\""+ MoumiConfig.getMessageBundle().getString("moumi.message.popup.selectUserInclude") +"\");\n");
			strbuf.append("	\n\n");
		}

		strbuf.append("	var uidList =\"" + id + "\";");
		strbuf.append("	var unameList=\"" + name + "\";");

		strbuf.append("	parent.uidList = uidList;");
		strbuf.append("	parent.unameList = unameList;");

		strbuf.append("	function movelist(){\n");
		strbuf.append("		var name = '';\n");
		strbuf.append("		var id = '';\n");
		strbuf.append("		var addForm = document.AddrList;\n");
		for (int i = 0; i < count; i++) {
			strbuf.append("		if(addForm.uname");
			strbuf.append(i);
			strbuf.append(".checked == false){\n");
			strbuf.append("			id += addForm.uid");
			strbuf.append(i);
			strbuf.append(".value+',';\n");
			strbuf.append("			name += addForm.uname");
			strbuf.append(i);
			strbuf.append(".value+',';\n");
			strbuf.append("		}\n\n");
		}

		strbuf.append("		parent.userFrameDel(name, id);\n");
		strbuf.append("	}\n\n");

		strbuf.append("	function alldeletelist(){\n");
		strbuf.append("		parent.userFrameDel('', '');\n");
		strbuf.append("	}\n\n");

		strbuf.append("	function AllSelect() {\n");
		strbuf.append("		var addForm = document.AddrList;\n");
		for (int i = 0; i < count; i++) {
			strbuf.append("		addForm.uname");
			strbuf.append(i);
			strbuf.append(".checked = true;\n");
		}
		strbuf.append("	}\n\n");

		strbuf.append("	function AllCancel() {\n");
		strbuf.append("		var addForm = document.AddrList;\n");
		for (int i = 0; i < count; i++) {
			strbuf.append("		addForm.uname");
			strbuf.append(i);
			strbuf.append(".checked = false;\n");
		}
		strbuf.append("	}\n\n");

		strbuf.append("</script>\n");

		/******************** HTML 생성 ********************/
		strbuf.append("<html>\n");
		strbuf.append("	<head></head>\n");
		strbuf.append("<link rel='stylesheet' href='/totsys/common/css/text.css' type='text/css'>\n");
		strbuf.append("<link rel='StyleSheet' href='/totsys/common/css/dtree.css' type='text/css' />\n");
		strbuf.append("<script type='text/javascript' src='/totsys/common/js/dtree.js'></script>\n\n");
		strbuf.append("	<body bgcolor=\"#FFFFFF\" text=\"#000000\" leftmargin=\"0\" topmargin=\"0\" marginwidth=\"0\" marginheight=\"0\" onload=\"setList()\">\n");
		strbuf.append("		<form name=AddrList method=Post>\n");
		strbuf.append("		<table border=0 cellpadding=5 cellspacing=2 width=100%>\n");
		if (count > 0) {
			strbuf.append("			<tr><td>"+ MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.submit")+ MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.request")+ MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.personal") +" (" + count + ")</td></tr>\n");
			strbuf.append("			<tr><td><span style='cursor:hand' onclick='AllSelect()'>"+ MoumiConfig.getMessageBundle().getString("moumi.message.button_small.selectAll") +"</span> | <span style='cursor:hand' onclick='AllCancel()'>"+ MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.all") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.cancel") +"</span></td></tr>\n");
		}
		strbuf.append("			<tr>\n");
		strbuf.append("				<td>\n");

		for (int i = 0; i < count; i++) {
			strbuf.append("					<input type=checkbox name=uname");
			strbuf.append(i);
			strbuf.append(" value=\"");
			strbuf.append(arrayName[i]);
			strbuf.append("\" onclick=\"\"><font size=2 face=\"돋움\">");
			strbuf.append(arrayName[i]);
			strbuf.append("</font><br>\n");
			strbuf.append("					<input type=hidden name=uid");
			strbuf.append(i);
			strbuf.append(" value=\"");
			strbuf.append(arrayID[i]);
			strbuf.append("\">\n");
		}

		strbuf.append("				</td>\n");
		strbuf.append("			</tr>\n");
		strbuf.append("		</table>\n");
		strbuf.append("		</form>\n");
		strbuf.append("	</body>\n");
		strbuf.append("</html>\n");

		return strbuf.toString();
	}

}
