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 BBSManagerBBSServlet 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)
		{}
	}
	
	
	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("function show()");
		out.println("{ ");
		out.println("	var temp = document.form1.targetName.value ;");
		out.println("	var one = temp.indexOf('부', 0); ");
		out.println("	var two = temp.indexOf('팀', one); ");
		out.println("	if ( one == -1 )");
		out.println("	{");
		out.println("		document.form1.Department.value = temp.substring ( 0, two);");
		out.println("		document.form1.Team.value = '' ;");
		out.println("	}");
		out.println("	else");
		out.println("	{");
		out.println("		document.form1.Department.value = temp.substring( 0, one+1 );");
		out.println("		if ( temp.substring( one+1, two+1 ) == '팀' ) ");			
		out.println("			document.form1.Team.value = ''; ");
		out.println("		else document.form1.Team.value = temp.substring( one+1, two+1 ); ");
		out.println("	}");
		out.println("	document.form1.BoardName.value = temp.substring( two+1 );");		
		out.println("	document.form1.old.value = temp;");
		out.println("}");
		out.println("");

		out.println("function deleteBoard( )");
		out.println("{");
		out.println("	if ( document.form1.Department.value.length == 0)	alert( '부서이름이 없습니다.' );");
		out.println("	else if ( document.form1.BoardName.value.length == 0 ) alert( '게시판이름이 없습니다.' );");
		out.println("	else {");
		out.println("		var de = confirm('석택된 게시판의 모든 데이타가 지워집니다. \\n\\n삭제하시겠습니까?');");
		out.println("		if ( de )	{");
		out.println("			document.form1.type.value = 'delete';");
		out.println("			document.form1.submit();	}");
		out.println("		else alert( '게시판 삭제가 취소되었습니다.');");
		out.println("	}");
		out.println("}");

		out.println("function changeName( )");
		out.println("{");
		out.println("	var old = document.form1.targetName.value;");
		out.println("	old = old.substring ( old.indexOf('팀') +1, old.length );");
		out.println("	var name = document.form1.BoardName.value ;");		
		out.println("	if ( document.form1.Department.value.length == 0)	alert( '부서이름이 없습니다.' );");
		out.println("	else if ( old ==  name ) alert(\"새로운 게시판 이름을 입력하십시요.\"); "); 
		out.println("	else ");
		out.println("	{");
		out.println("		var re = confirm('선택된 게시판의 이전데이타는 새로운 게시판이름으로 변경됩니다. \\n\\n이름 변경 하시겠습니까?');");
		out.println("		if ( re )	{ ");
		out.println("			document.form1.type.value = 'rename';");
		out.println("			document.form1.submit();	}");
		out.println("		else alert( '게시판 이름변경이 취소되었습니다.');");		
		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("<br>");
				
		// 타이틀....
		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/BBSManagerBBSServlet\">");		
		
		// 테이블 시작..
		out.println("<table align=\"center\" cellpadding=\"1\" width=500>");
				
		// 테이블 색상을 넣는곳..
		String option1 = "bgcolor = \"#C7E4FF\" width=250";			// 첫열
		String option2 = "";															// 두번째 열

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

		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 size=30 name=\"Department\" ></td>");
		out.println("  </tr>");			
		
		out.println("  <tr>");
		out.println("    <td " + option1 + "><font size=2>팀이름은?</font></td>");
		out.println("    <td " + option2 + "><input type=text size=30 name=\"Team\" ></td>");
		out.println("  </tr>");

		out.println("  <tr>");
		out.println("    <td  " + option1 + "><font size=2>게시판 이름은?</font></td>");
		out.println("    <td " + option2 + "><input type=text size=30 name=\"BoardName\"></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("<input type=hidden name=old>");

		out.println("  <p align=center><font size=\"2\">");
		out.println("	<input type=\"button\" value=\" 삭  제 \" onClick='deleteBoard()'>");
		out.println("	<input type=\"button\" value=\" 이름변경 \" onClick='changeName()'>");
		out.println("	<input type=\"button\" value=\"원래대로\" onClick='show()'></font></p>");
		
		out.println("</form>");
		
		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"));
	
		String BoardName = req.getParameterValues("BoardName")[0];
		BoardName = new String ( BoardName.getBytes("ISO-8859-1"), "EUC-KR");
		System.out.println( BoardName +"<br>");

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

		String oldbbsID = req.getParameterValues("old")[0];
		oldbbsID = new String ( oldbbsID.getBytes("ISO-8859-1"), "EUC-KR");
		System.out.println( oldbbsID +"<br>");		
		
		
		// 게시판이름은 부서+팀+boardname 까지 입니다..
		String bbsID = oldbbsID.substring( 0, oldbbsID.lastIndexOf("팀")+1 ) + BoardName;
		System.out.println( " 게시판의 이름은 " + bbsID +"<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( "delete") )
		{
			System.out.println("삭제입니다.");
			bbsResultStatus = bbsController.deleteBBS( oldbbsID );
		}
		else if ( type.equals( "rename") )
		{	
			System.out.println("이름 변경입니다.");
			bbsResultStatus = bbsController.renameBBS( oldbbsID, bbsID );
		}
		
		if(bbsResultStatus.getResultStatus() == 0)
		{
			out.println("<p align=center> 작업이 성공하였습니다.<br><br>");
			out.println("<a href='/servlet/BBSManagerBBSServlet' target=\"_self\" onClick=\"parent.frames['contents'].location='/servlet/BBSTreeServlet'\"><image border=0 src=\"../image/BBS_back.gif\" alt='돌아가기'></a></p>");
		}
		else
		{
			out.println( "<p align=center>게시판 작업이 실패하였습니다.<br><br>");		
			out.println("<a href='/servlet/BBSManagerBBSServlet' target=\"_self\" onClick=\"parent.frames['contents'].location='/servlet/BBSTreeServlet'\"><image border=0 src=\"../image/BBS_back.gif\" alt='돌아가기'></a></p>");
		}

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

}