import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.etri.groupware.*;
import com.etri.groupware.bbs.*;
import com.etri.groupware.organization.*;

public class ClubMemeberManagerServlet extends HttpServlet
{

	GroupwareControllerInterface groupwareController=null;
	BBSControllerInterface bbsController = null;
	ResultStatus bbsResultStatus = null;
	Properties pro=null;
	
	public void init(ServletConfig sc) throws ServletException
	{
		super.init(sc);
		
		//그룹웨어 컨트롤러를 생성한다.
		//먼저 프라퍼티를 생성한다.
		pro = new Properties();

		//DB매너저 구현 클래스 이름 설정
		pro.put("OrganizationDBManagerClassName", "PandaSoftOrganizationDBManager");
		pro.put("BBSDBManagerClassName", "PandaSoftBBSDBManager");
		pro.put("EDADBManagerClassName", "PandaSoftEDADBManager");
		pro.put("MailDBManagerClassName", "PandaSoftMailDBManger");
		
		try
		{
			groupwareController = GroupwareController.init( pro );
			System.out.println("그룹웨어 컨트롤러 생성을 마쳤습니다.");
			
			//게시판 관리 컨트롤러를 가져온다.
			bbsController = groupwareController.createBBSController();
			System.out.println("게시판 컨트롤러 생성도 무사히 마쳤습니다.");
		}
		catch(Exception e)
		{ System.out.println( e.toString() ); }
	}
	
	public void destroy()
	{
		super.destroy();
		DBConnectionManager.instance.release();
		System.out.println("destory 끝...");
	}
	
	/*----------------------------------------------------------------- */
	/**
	 [메소드이름]: doGet<br>
	 [기능]: 동아리회원의 가입과 탈퇴를 관리하는 서블릿<br>
	 [파라미터]: HttpServletRequest req, HttpServletResponse res<br>
	 [호출자] : 사용자<br>
	 */
	/*--------------------------------------------------------------- */			
	public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
	{
		// session 확인하는곳....		
		HttpSession session = req.getSession(true);
		
		boolean authentication = false ;
		String kind = null ;
		String id = null ;
		String name = null ;
		
		if ((session.isNew()))
		{
			session.invalidate();
			res.sendRedirect("../Login.html");
		}
	    else if(session.getValue("Authentication").equals("true")){
	    	authentication = true;
            kind = (String)session.getValue("Kind");
            id = (String)session.getValue("Id");
            name = (String)session.getValue("Name");          
       }
       else {
            session.invalidate();
            res.sendRedirect("../Login.html");
       }
	   // session 확인 끝!!!	

		res.setContentType("text/html; charset=euc-kr");
		// 캐쉬를 못하도록..
		res.setHeader("cache-control", "no-cache");
		PrintWriter out = new PrintWriter(new OutputStreamWriter(res.getOutputStream(), "EUC-KR"));

		out.println("<html>");
		
		out.println("<head>");
		out.println("<title>동아리</title>");
		
		out.println("<script language=\"JavaScript\">");
		out.println("<!--");
		
		// 새로운 윈도우 창을 뛰워서, 접근권한을 설정할 예정입니다..
		out.println("var myWin ;");		
		out.println("function createClub() {");
		out.println("	myWin = window.open ( \"../clubSelection.html\", '' , \"width=650,height=370,scrollbars=1,copyHistory=1\" ) ;");
		out.println("}");

		out.println("function result( )");
		out.println("{");
		out.println("	var memeber = arguments[0] ;");
		out.println("	document.form1.newMemeber.value = memeber ;");
		out.println("	myWin.close();");
		out.println("}");
	
		out.println("function show()");
		out.println("{");
		out.println("	for ( var j=0 ; document.form1.memeberList[j] != null ; )");
		out.println("	{");
		out.println("		document.form1.memeberList[j] = null ;");
		out.println("	}");
		out.println("");
		out.println("	var teamId = document.form1.name.value ;");
		out.println("	var index = teamId.indexOf( \";\" );");
		out.println("	teamId = teamId.substring( index +1, teamId.length );");
		out.println("	var length = teamId.length;");
		out.println("");
		out.println("	if ( length == 0 )");
		out.println("	{");
		out.println("		alert ( \"동아리 회원이 없습니다.\" ) ;");
		out.println("	}");
		out.println("	else");
		out.println("	{");
		out.println("		for ( var i=0; length > i ;) {");
		out.println("			var position = teamId.indexOf ( \";\", i ) ;");
		out.println("			var temp = teamId.substring ( i , position ) ;");
		out.println("			var newElement = document.createElement(\"OPTION\");");
		out.println("			newElement.text = temp ;");
		out.println("			newElement.value = temp ;");
		out.println("			document.form1.memeberList.options.add( newElement ) ;");
		out.println("			i = position + 1;");
		out.println("		}");
		out.println("	}");
		out.println("}");

		out.println("function insertClub() ");		
		out.println("{");
		out.println("	if ( document.form1.newMemeber.value == '' ) alert('추가할 회원을 선택하여 주십시요.') ;");
		out.println("   	else");		
		out.println("  	{");		
		out.println("		document.form1.type.value = 'insert';");
		out.println("		document.form1.submit();");		
		out.println("   	}");		 
		out.println("}");		

		out.println("function deleteClub() ");		
		out.println("{");
		out.println("   var loop = document.form1.memeberList.length ;");		
		out.println("   var list = '';");	
		out.println("   	if ( document.form1.memeberList.selectedIndex == -1 ) alert('삭제할 회원을 선택하세요.');");
		out.println("   	else");		
		out.println("  	{");		
		out.println("      	for ( var i=0; i < loop; i++) ");		
		out.println("		{");		
		out.println("   			if ( document.form1.memeberList[i].selected) ");		
		out.println("	   		{");		
		out.println("		    	list = list + document.form1.memeberList[i].value + \";\" ; ");	
		out.println("		   		document.form1.memeberList[i] = null ;");		
		out.println("		   		i = i - 1 ;");		
		out.println("		   		loop = loop - 1 ;");		
		out.println("	   		}");		
		out.println("     	}");		
		out.println("		document.form1.newMemeber.value = list ; ");		
		out.println("		document.form1.type.value = 'delete';");		
		out.println("		document.form1.submit();");		
		out.println("  	}");		
		out.println("}");

		out.println("//-->");		
		out.println("</script>");
		
		out.println("</head>");		
		

		out.println("<basefont size=2>");
		out.println( "<body bgcolor=white text=\"#0000FF\" link=\"#0000FF\" alink=\"#FF2020\" vlink=\"#000000\" onload='show()'>" ) ;
		
		// 게시판 우측에 들어가는 이미지...
		out.println("<p align=right><img src='../image/우측_게시판.gif'></p>");
		
		// 타이틀....
		out.println("<p align=\"center\"><font size=\"4\" color=\"gray\"><b>동아리 관리</b></font>");
		out.println("<hr width=500><br></p>");

		out.println("<form name=form1 method=\"POST\" action=\"/servlet/ClubMemeberManagerServlet\">");
		
		// 테이블 시작..
		out.println("<table align=\"center\" cellpadding=\"1\" width=500>");
		// 게시판 시작하면 보여주는 처음 화면 설정
		
		// 테이블 색상을 넣는곳..
		String option1 = "bgcolor = \"#C7E4FF\" width=200 align=center";			// 첫열
		String option2 = "";				// 두번째 열

		out.println("  <tr>");
		out.println("     <td " + option1 + "><font size=2>동아리를 선택하세요.</font></td>");
		out.println("     <td " + option2 + "><select style='width=140pt;' name=\"name\" onChange='show();'> ");		
			
		// 데이타 베이스에서 조직도 트리의 내용 즉, 부서와 팀을 가져온다.
		String[][] clubTree = bbsController.getClubTree ( ) ;
		for ( int i = 0 ; !(clubTree[i][0].equals("null")) ; i++ ) 
		{
			String value = clubTree[i][0] + ";";
			for ( int j = 1 ; !(clubTree[i][j].equals("null")) ; j++ )
			{
				if ( !clubTree[i][j].equals("null(null)") )
					value= value + clubTree[i][j] + ";" ;				
			}
			out.println("<option value='" + value + "'>"+ clubTree[i][0] +"</option> ");
		}

		out.println("</select></td>");
		out.println("  </tr>");			
		
		out.println("  <tr>");
		out.println("     <td " + option1 + "><font size=2>기존 회원 리스트</font></td>");
		out.println("     <td " + option2 + "><select multiple style='width=140pt;' name=\"memeberList\"' size='10'> ");		
		out.println("</select></td>");
		out.println("  </tr>");			

		out.println("  <tr>");
		out.println("     <td " + option1 + "><font size=2>회    원 리스트 </font></td>");
		out.println("     <td " + option2 + "><input type=text name='newMemeber' size='25' value=''>");
		out.println("			<input type=button value='조직도' onclick='createClub()'></td>");
		out.println("  </tr>");			

		out.println("</table>");
		out.println("<p align=center><hr width=500></p>");
		
		out.println("<input type=hidden name=type>");

		out.println("  <p align=center><font size=\"2\"><input type=\"button\" value=\" 신    규 \" onClick='insertClub()'>   ");
		out.println("		<input type=\"button\" value=\" 탈    퇴 \" onClick='deleteClub()'> </font></p>");
		out.println("</form>");
		
		out.println("<br><br>");		

		out.println("</body>");
		out.println("</html>");
		
		out.close();
		
	}

	/*----------------------------------------------------------------- */
	/**
	 [메소드이름]: doPost<br>
	 [기능]: 동아리회원의 가입과 탈퇴를 관리하는 서블릿<br>
	 [파라미터]: HttpServletRequest req, HttpServletResponse res<br>
	 [호출자] : 사용자<br>
	 */
	/*--------------------------------------------------------------- */			
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
	{
		
		// session 확인하는곳....		
		HttpSession session = req.getSession(true);
		
		boolean authentication = false ;
		String kind = null ;
		String id = null ;
		String name = null ;

		if ((session.isNew()))
		{
			session.invalidate();
			res.sendRedirect("../Login.html");
		}
	    else if(session.getValue("Authentication").equals("true")){
	    	authentication = true;
            kind = (String)session.getValue("Kind");
            id = (String)session.getValue("Id");
            name = (String)session.getValue("Name");          
       }
       else {
            session.invalidate();
            res.sendRedirect("../Login.html");
       }
	   // session 확인 끝!!!		*/

		res.setContentType("text/html; charset=euc-kr");
		PrintWriter out = new PrintWriter(new OutputStreamWriter(res.getOutputStream(),"EUC-KR"));

		System.out.println( " post 입니다.<br>");

		String clubName = req.getParameterValues("name")[0];
		clubName = new String ( clubName.getBytes("ISO-8859-1"), "EUC-KR");
		if ( clubName.indexOf(";") != -1 )
			clubName = clubName.substring ( 0, clubName.indexOf(";") );
		System.out.println( clubName +"<br>");
			
		String memeberList = req.getParameterValues("newMemeber")[0];
		memeberList = new String ( memeberList.getBytes("ISO-8859-1"), "EUC-KR");
		System.out.println( memeberList +"<br>");

		String type = req.getParameterValues("type")[0];
		type= new String ( type.getBytes("ISO-8859-1"), "EUC-KR");
		System.out.println( type +"<br>" );


		out.println("<html><body>");

		out.println("<basefont size=2>");
		out.println( "<body bgcolor=white text=\"#0000FF\" link=\"#0000FF\" alink=\"#FF2020\" vlink=\"#000000\">" ) ;
		
		// 게시판 우측에 들어가는 이미지...
		out.println("<p align=right><img src='../image/우측_게시판.gif'></p>");
		
		if ( type.equals("insert") )
			bbsResultStatus = bbsController.clubInsert ( clubName, memeberList);
		else if ( type.equals("delete") )
			bbsResultStatus = bbsController.clubDelete( clubName, memeberList );

		if(bbsResultStatus.getResultStatus() == 0)
		{
			out.println("<p align=center> 작업이 성공하였습니다.<br><br>");
			out.println("<a href='/servlet/BBSTreeServlet' target=\"contents\" onClick=\"parent.frames['detail'].location='/servlet/ClubMemeberManagerServlet'\"><image border=0 src=\"../image/BBS_back.gif\" alt='돌아가기'></a></p>");
		}
		else
		{
			out.println( "<p align=center>게시판 작업이 실패하였습니다.<br><br>");		
			out.println("<a href='/servlet/BBSTreeServlet' target=\"contents\" onClick=\"parent.frames['detail'].location='/servlet/ClubMemeberManagerServlet'\"><image border=0 src=\"../image/BBS_back.gif\" alt='돌아가기'></a></p>");
		}

		out.println("</body></html>");
		
		out.close();
	}
		

}