/***********************************************************************************
 * @@ 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.lang.Encoder;
//import kr.co.kihyun.lang.MInteger;
//import kr.co.kihyun.lang.MLong;
import kr.co.kihyun.moumi.MoumiConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebServlet("/servlet/kr.co.kihyun.beans.user.HttpDeptAllList")
public class HttpDeptAllList extends HttpServlet {
        private static final Logger LOG = LoggerFactory.getLogger(HttpDeptAllList.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 nameList;
		String idList;
		String uidList;
		String topID;
		req.getParameter("partID");
		nameList = Encoder.toJava(req.getParameter("nameList"));
		idList = req.getParameter("idList");
		uidList = req.getParameter("uidList");
		topID = req.getParameter("topid");
		req.getParameter("selectType");

		// if(!MString.isNull(tempPartID)){
		// out.println(getLeftList(tempPartID, selectType));
		// out.println(getLeftTreeList(tempPartID, selectType));
		// }else if(!MString.isNull(idList)){
		// out.println(getRightList(nameList, idList, uidList, topID));
                
                //v2. 9.크로스사이트 스크립트 (PrintWrier) : Update by KWON,HAN  
//		out.println(getRightCheckList(nameList, idList, uidList, topID));
                
                // 수정 : 외부 입력값 필터링
                String filtered_nameList = nameList.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
                String filtered_idList = idList.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
                String filtered_uidList = uidList.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
                String filtered_topID = topID.replaceAll("<","").replaceAll(">","").replaceAll("&","").replaceAll(",","");
                LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpDeptAllList.doPost() filtered_nameList={}, Not Test", filtered_nameList);
                LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpDeptAllList.doPost() filtered_idList={}, Not Test", filtered_idList);
                LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpDeptAllList.doPost() filtered_uidList={}, Not Test", filtered_uidList);
                LOG.debug("v2 9.크로스사이트 스크립트 (PrintWrier) : HttpDeptAllList.doPost() filtered_topID={}, Not Test", filtered_topID);
                out.println(getRightCheckList(filtered_nameList, filtered_idList, filtered_uidList, filtered_topID)); 
                //========================================                
		// }
	}

	private String getRightCheckList(String name, String id, String uid, String topID) {
		StringBuffer strbuf = new StringBuffer();
		// String[] arrayName = name.split(",");
		String[] arrayName = null;
		DeptView deptView = new DeptView();
		DeptList deptList = new DeptList();

		String[] arrayID = id.split(",");
		String[] arrayUID = uid.split(","); // 선택된사용자 아이디 리스트
		int count = 0;
		int ucount = 0;
		int change = 0;

		if (id.equals("") || id == null)
			count = 0;
		else if (arrayID.length > 0) {
			count = arrayID.length;
		}

		if (uid.equals("") || uid == null)
			ucount = 0;
		else if (arrayUID.length > 0) {
			ucount = arrayID.length;
		}

		if (topID != null) {
			int allCount = 0;
			String[] allList = null;

			deptList.executeIDList(topID);

			allCount = deptList.getCount();
			allList = deptList.getIDList();

			if (allCount > 0) {
				int same;
				for (int i = 0; i < allCount; i++) {

					same = 0;
					for (int j = 0; j < count; j++) {
						if (arrayID[j].equals(allList[i])) {
							same = 1;
							break;
						}
					}
					if (same == 0) {
						int isEquals = 0;
						String[] tmp = null;
						for (int j = 0; j < ucount; j++) {
							if (arrayUID.length > j)
								tmp = arrayUID[j].split("/"); // UID[j]의 ArrayOutOfBoundsException 방지
							if (tmp.length > 1) { // tmp[1]의 ArrayOutOfBoundsException 방지
								if (tmp[1].equals(allList[i])) { // 선택된 사용자의 부서와 선택된 부서 중 같은게 있는지 검사
									isEquals = 1;
									change = 1;
									break;
								}
							}
						}

						if (isEquals == 0) {
							if (id == null || id.equals("")) {
								id = allList[i].toString();
							} else {
								id = id + "," + allList[i];
							}
						}
					}
				}
			}
		} else {
			throw new NullPointerException();
		}

		arrayID = id.split(",");
		name = null;

		if (arrayID.length > 0 && !(id.equals(""))) {
			count = arrayID.length;

			arrayName = new String[count];
			for (int i = 0; i < count; i++) {
                                //v2. 6.SQL 삽입 : deptView.executeQuery에서 prepare SQL 문으로 되어 있다.
				deptView.executeQuery(arrayID[i]);
                                //================
				arrayName[i] = deptView.getPartName() + "-" + deptView.getName();
			}

			name = arrayName[0];
			for (int i = 1; i < count; i++) {
				name = name + "," + arrayName[i];
			}
		}

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

		if (change == 1) {
			strbuf.append("	alert("+MoumiConfig.getMessageBundle().getString("moumi.message.popup.selectDeptInclude")+");\n");
			strbuf.append("	\n");
		}

		strbuf.append("	var orgidList='';\n");
		strbuf.append("	var orgnameList='';\n\n");

		strbuf.append("	var selidList='';\n");
		strbuf.append("	var selnameList='';\n\n");

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

		strbuf.append("	function setList() {\n");
		strbuf.append("		parent.idList = \"" + id + "\";\n");
		strbuf.append("		parent.nameList = \"" + name + "\";\n");
		strbuf.append("		orgidList = \"" + id + "\";\n");
		strbuf.append("		orgnameList = \"" + name + "\";\n");
		strbuf.append("		selidList=orgidList+',';\n");
		strbuf.append("		selnameList=orgnameList+',';\n");
		strbuf.append("	}\n\n");

		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.name");
			strbuf.append(i);
			strbuf.append(".checked == false){\n");
			strbuf.append("			id += addForm.id");
			strbuf.append(i);
			strbuf.append(".value+',';\n");
			strbuf.append("			name += addForm.name");
			strbuf.append(i);
			strbuf.append(".value+',';\n");
			strbuf.append("		}\n\n");
		}
		strbuf.append("		parent.leftFrameDel(name, id);\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.name");
			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.name");
			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("	<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");
		strbuf.append("			<tr><td>"+ MoumiConfig.getMessageBundle().getString("moumi.message.tot_report.submit") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.request") + MoumiConfig.getMessageBundle().getString("moumi.message.tot_doc.devision") +" (" + 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=name");
			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=id");
			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();
	}

}
