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 BBSCreateBBSServlet extends HttpServlet
{

	GroupwareControllerInterface groupwareController=null;
	OrganizationManagementControllerInterface omc = 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 );
			
			//게시판 관리 컨트롤러를 가져온다.
			bbsController = groupwareController.createBBSController();
			
			// 조직의 부와 팀을 가져오기 위해서 조직도 controller를 생성한다.
			omc = groupwareController.createOrganizationManagementController ( ) ;
		}
		catch(Exception e)
		{}
	}
	
	public void destroy()
	{
		super.destroy();
		DBConnectionManager.instance.release();
	}
	
	/*----------------------------------------------------------------- */
	/**
	 [메소드이름]: 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");
       }
	   
		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("<!--");
		
		// form을 전송하기 전에 적당한 데이타가 입력되었는지 체크하는곳
		out.println("function Check_Form(form)");
		out.println("{");
		out.println("	var boardname='';");
		out.println("	for( var i = 0; i < form.BoardName.value.length; i++)");
		out.println("		boardname= boardname + ' ';");
		out.println("	if(form.Department.value.length == 0) alert(\"부서를 선택하여 주십시요.\");");
		out.println("    else if(form.BoardName.value.length == 0) alert(\"게시판이름을 입력하여 주십시요.\");");
		out.println("	else if (form.BoardName.value == boardname ) alert(\"게시판이름을 입력하여 주십시요.\");");
		out.println("    else form.submit();");
		out.println("}");
		
		// 부서가 선택되면 그 부서에 속한 팀 리스트를 보여주는 곳
		out.println("function selectTeam()");
		out.println("{ ");
		out.println("	for ( var j=0 ; document.form1.Team[j] != null ; )");
		out.println("	{");
		out.println("		document.form1.Team[j] = null ;");
		out.println("	}");
		out.println("	document.form1.BoardName.value = \"\";");
		out.println("");
		out.println("	var teamId = document.form1.Department.value ;");
		out.println("	var department = teamId.indexOf( \";\" );");
		out.println("	teamId = teamId.substring( department +1, teamId.length );");
		out.println("	var length = teamId.length;");
		out.println("");
		out.println("	if ( length == 0 )");
		out.println("	{");
		out.println("		var element = document.createElement(\"OPTION\");");
		out.println("		element.text = \"없음\" ;");
		out.println("		element.value = \"팀\" ;");
		out.println("		document.form1.Team.options.add( element ) ;");
		out.println("		alert ( \"이 부서에는 팀이 존재하지 않습니다.\" ) ;");
		out.println("	}");
		out.println("	else");
		out.println("	{");
		out.println("		var element = document.createElement(\"OPTION\");");
		out.println("		element.text = \"없음\" ;");
		out.println("		element.value = \"팀\" ;");
		out.println("		document.form1.Team.options.add( element ) ;");
		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("			if ( temp != '' )");
		out.println("			{");
		out.println("				newElement.text = temp ;");
		out.println("				newElement.value = temp ;");
		out.println("				document.form1.Team.options.add( newElement ) ;");
		out.println("			}");
		out.println("			i = position + 1;");
		out.println("		}");
		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='selectTeam();'>" ) ;
		
		// 게시판 우측에 들어가는 이미지...
		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=400><br></p>");

		out.println("<form name=form1 method=\"POST\" action=\"/servlet/BBSCreateBBSServlet\">");
		out.println("<table align=\"center\" cellpadding=\"1\" width=400>");
				
		// 테이블 색상을 넣는곳..
		String option1 = "bgcolor = \"#C7E4FF\" width=150";			// 첫열
		String option2 = "";															// 두번째 열

		out.println("  <tr>");
		out.println("     <td " + option1 + "><font size=2>부이름은?</font></td>");
		out.println("     <td " + option2 + "><select style='width=115pt;' name=\"Department\" onChange='selectTeam()'> ");		
		out.println("<option value='회사;;'>회사</option>");
		
		// 데이타 베이스에서 조직도 트리의 내용 즉, 부서와 팀을 가져온다.
		String[][] departmentAndTeam = omc.getOrganizationTree ( ) ;
		
		// 부서 리스트
		for ( int o=0 ; !(departmentAndTeam[o][0].equals("null")) ; o++ ) 
		{
			String teamList = departmentAndTeam[o][0] + ";";
			//팀 리스트
			for ( int p=1 ; !(departmentAndTeam[o][p].equals("null")) ; p++ )
				teamList = teamList + departmentAndTeam[o][p] + ";";
			out.println("<option value='" + teamList + "'>"+ departmentAndTeam[o][0]+"</option> ");
		}
		
		out.println("</select></td>");
					
		// 오늘 기준으로 며칠전까지 보여주나...
		out.println("  <tr>");
		out.println("    <td " + option1 + "><font size=2>팀이름은?</font></td>");
		out.println("    <td " + option2 + "><select style='width=115pt;' name=\"Team\">");
		out.println("</tr>");

		// 화면당 몇개의 게시물을 보여줄것인가?
		out.println("  <tr>");
		out.println("    <td  " + option1 + "><font size=2>게시판 이름은?</font></td>");
		out.println("    <td  " + option2 + "><input type=\"text\" name=\"BoardName\" size=\"20\"><font size=2 color=black> 게시판</font></td>");
		out.println("  </tr>");
		
		out.println("</table>");
		out.println("<p align=center><hr width=400></p>");

		out.println("  <p align=center><font size=\"2\"><input type=\"button\" value=\"전    송\" onClick='Check_Form( this.form);'>  <input type=\"button\" value=\"원래대로\" onClick='selectTeam();'></font></p>");
		out.println("</form>");
		
		out.println("<br><br>");		
		out.println("<table width=400 align=center>");
		out.println("<tr align=center><font color=red><b>게시판 만들기의 주의사항</b></font><br></tr>");
		out.println("<tr><hr width=400></tr>");
		out.println("<tr>");
		out.println("<font color=blue>1. 부서게시판 만들기 :</font><font color=black> 부서이름 선택, 팀이름은 '없음', 게시판이름을 기재합니다.<br></font>");
		out.println("<font color=blue>2. 팀게시판 만들기   :</font><font color=black> 부서이름, 팀이름을 선택, 게시판이름을 기재합니다.<br></font>");		
		out.println("</tr>");
		out.println("</table>");
		
		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");
       }
		
		res.setContentType("text/html; charset=euc-kr");
		PrintWriter out = new PrintWriter(new OutputStreamWriter(res.getOutputStream(),"EUC-KR"));

		String Department = req.getParameterValues("Department")[0];
		Department = new String ( Department.getBytes("ISO-8859-1"), "EUC-KR");
		Department = Department.substring( 0, Department.indexOf (";") );
		System.out.println( Department );

		String Team = req.getParameterValues("Team")[0];
		Team = new String ( Team.getBytes("ISO-8859-1"), "EUC-KR");
		System.out.println( Team );
		
		String BoardName = req.getParameterValues("BoardName")[0];
		BoardName = new String ( BoardName.getBytes("ISO-8859-1"), "EUC-KR");
		System.out.println( BoardName );

		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>");

		// 게시판이름은 부서+팀+boardname 까지 입니다..
		String bbsID = Department + Team +BoardName;		
		bbsResultStatus = bbsController.createBBS( Department, Team,  bbsID);		
		if(bbsResultStatus.getResultStatus() == 0)
		{
			if ( Team.equals( "팀") )
				out.println("<p align=center>"+ Department + " " + BoardName + "  게시판 만들어 졌습니다.<br><br>");
			else
				out.println("<p align=center>"+ Department + " " + Team  + " " + BoardName + "  게시판 만들어 졌습니다.<br><br>");

			out.println("<a href='/servlet/BBSTreeServlet' target=\"contents\" onClick=\"parent.frames['detail'].location='/servlet/BBSCreateBBSServlet'\"><image border=0 src=\"../image/BBS_back.gif\" alt='돌아가기'></a></p>");
		}
		else
		{
			if ( Team.equals( "팀") )
				out.println( "<p align=center>"+ Department +  " " + BoardName + " 게시판은 이미 존재합니다.<br><br>");		
			else
				out.println( "<p align=center>"+ Department + " " + Team  + " " + BoardName + " 게시판은 이미 존재합니다.<br><br>");		

			out.println("<a href='/servlet/BBSTreeServlet' target=\"contents\" onClick=\"parent.frames['detail'].location='/servlet/BBSCreateBBSServlet'\"><image border=0 src=\"../image/BBS_back.gif\" alt='돌아가기'></a></p>");
		}

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