/*
	개인 정보
*/

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.authentication.* ;

public class BBSOptionPropertyServlet 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>
	 [기능]: 사용자가 Option을 설정하는 서블릿<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 ;
		String department = null;
		String team = 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");          
            department = (String)session.getValue("Department");
            team = (String)session.getValue("Team");
       }
       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"));				

		OptionProperty option = bbsController.getPersonalOption( id );
		      
		out.println("<html><head><title>개인 정보</title>");
		out.println("<script language=\"JavaScript\">");
		out.println("<!--");
		
		// form을 전송하기 전에 적당한 데이타가 입력되었는지 체크하는곳
		out.println("function Check_Form(form)");
		out.println("{");
		out.println("     if(form.word.value.length == 0 )");
		out.println("	{ ");
		out.println("     	con = confirm('키워드 검색 기능을 설정하지 않으시겠습니까?');  ");
		out.println("     	if( con == true )");
		out.println("		{ ");
		out.println("			form.title.checked = false; form.author.checked = false; form.content.checked = false;");
		out.println("			form.submit(); ");
		out.println("		}");
		out.println("     	else alert(\"키워드 검색기능을 설정하여 주십시요.\"); ");
		out.println("	}");
		out.println("     else");
		out.println("	{ ");
		out.println("		if ( form.title.checked == false && form.author.checked == false && form.content.checked == false)");
		out.println("			alert('성명, 제목, 본문중 하나를 선택하여 주십시요.');");
		out.println("		else");
		out.println("		{");
		out.println("	     	if( form.title.checked == true )  form.title.value = form.word.value; ");
		out.println("    	 	if( form.author.checked == true )  form.author.value = form.word.value; ");
		out.println("     		if( form.content.checked == true )  form.content.value = form.word.value; ");
		out.println("     		form.submit(); ");
		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\">" ) ;		

		// 게시판 우측에 들어가는 이미지...
		out.println("<p align=right><img src='../image/우측_게시판.gif'></p>");
		
		// 타이틀....
		out.println("<p align=center><font size=\"4\" color=\"gray\"><b>사용자 환경 설정</b></font></p>");
		out.println("<hr width=500>");
		
		// 폼 태그 
		out.println("<form method=\"post\" action=\"/servlet/BBSOptionPropertyServlet\">");
			
		// 테이블 시작..
		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>&nbsp;&nbsp;첫화면은?</font></td>");
		out.println("     <td " + option2 + "><select style='width=150pt;' name=\"firstBoard\">");

		// 게시판 리스트를 가져와야 합니다.
		String[][][] bbsList = bbsController.getBBStree();
		
		if ( kind.equals("user") )
		{
			System.out.println("사용자 입니다.");
		
			if ( option != null )
			{
				for( int i = 0 ; !(bbsList[i][0][0].equals("null"))  ; i ++ )
				{
					for ( int j = 1; !(bbsList[i][j][0].equals("null")) ; j++ )
					{
						for ( int k = 1 ; !(bbsList[i][j][k].equals("null")) ; k ++ )
						{
							// 회사 전체 게시판을 보여주기 위해서 check
							if ( bbsList[i][0][0].equals("회사") )
							{
								if ( option.getFirstBoard().equals( bbsList[i][j][k] ) )
									out.println("<option value='" + bbsList[i][j][k] +"' selected> 회사 " +  bbsList[i][j][k].substring(3) +" </option>");
								else
									out.println("<option value='" + bbsList[i][j][k] +"'> 회사 " +  bbsList[i][j][k].substring(3) + " </option>");
								
							}
							else  if ( bbsList[i][0][0].equals("동아리") )
							{
								String[] club = bbsController.getClub( id );
								if ( club != null )
								{
									for ( int no=0; no < club.length ; no++)
									{
										if ( bbsList[i][j][k].substring(4).equals( club[no] ) )
										{
											if ( option.getFirstBoard().equals( bbsList[i][j][k] ) )	
												out.println("<option value='" + bbsList[i][j][k] +"' selected> 동아리 "+ bbsList[i][j][k].substring( 4 ) +" </option>");
											else
												out.println("<option value='" + bbsList[i][j][k] +"'> 동아리 "+ bbsList[i][j][k].substring( 4 ) +" </option>");
										}
									}
								}
							}
							else if ( bbsList[i][0][0].equals( department ) )
							{
								if ( bbsList[i][j][0].equals("팀") )
								{
									System.out.println("자신이 첫게시판으로 지정했던 게시판");
									if ( option.getFirstBoard().equals( bbsList[i][j][k] ) )
										out.println("<option value='" + bbsList[i][j][k] +"' selected> "+ bbsList[i][j][k]+" </option>");
									else
										out.println("<option value='" + bbsList[i][j][k] +"'> "+ bbsList[i][j][k]+" </option>");
								}
								else if ( bbsList[i][j][0].equals( team ) | team.equals( "null" ) )
								{
									if ( option.getFirstBoard().equals( bbsList[i][j][k] ) )
										out.println("<option value='" + bbsList[i][j][k] +"' selected> "+ bbsList[i][j][k]+" </option>");
									else
										out.println("<option value='" + bbsList[i][j][k] +"'> "+ bbsList[i][j][k]+" </option>");
								}		// if end
								
							}// 회사, 동아리, 부, 팀 게시판을 사용자에 따라서 보여준다.
	
						}		// "k" end
					}		// "j" end
				}		// i end.
			}		// option 이 설정되어 있을 때 모두보여주기, 끝.
			else		
			{
				for( int i = 0 ; !(bbsList[i][0][0].equals("null"))  ; i ++ )
				{
					for ( int j = 1; !(bbsList[i][j][0].equals("null")) ; j++ )
					{
						for ( int k = 1 ; !(bbsList[i][j][k].equals("null")) ; k ++ )
						{
							// 회사 전체 게시판을 보여주기 위해서 check
							if ( bbsList[i][0][0].equals("회사") )
								out.println("<option value='" + bbsList[i][j][k] +"'> 회사 " +  bbsList[i][j][k].substring(3) + " </option>");

							else  if ( bbsList[i][0][0].equals("동아리") )
							{
								String[] club = bbsController.getClub( id );
								if ( club != null )
								{
									for ( int no=0; no < club.length ; no++)
									{
										if ( bbsList[i][j][k].substring(4).equals( club[no] ) )
										{
											out.println("<option value='" + bbsList[i][j][k] +"'> 동아리 "+ bbsList[i][j][k].substring( 4 ) +" </option>");
										}
									}
								}
							}
							else if ( bbsList[i][0][0].equals( department ) )
							{
								if ( bbsList[i][j][0].equals("팀") )
								{
									out.println("<option value='" + bbsList[i][j][k] +"'> "+ bbsList[i][j][k]+" </option>");
								}
								else if ( bbsList[i][j][0].equals( team ) | team.equals( "null" ) )
								{
									out.println("<option value='" + bbsList[i][j][k] +"'> "+ bbsList[i][j][k]+" </option>");
								}		// if end
								
							}// 회사, 동아리, 부, 팀 게시판을 사용자에 따라서 보여준다.
	
						}		// "k" end
					}		// "j" end
				}		// i end.
			}		// option 이 설정되어 있지 않을때 모두 보여주기, 끝.
		}
		
	//======================================= 사용자와 관리자가 경계선 ==========================//
	
		else	if ( kind.equals( "manager" ) )
		{			
			for( int i = 0 ; !(bbsList[i][0][0].equals("null"))  ; i ++ )
			{
				for ( int j = 1; !(bbsList[i][j][0].equals("null")) ; j++ )
				{
					for ( int k = 1 ; !(bbsList[i][j][k].equals("null")) ; k ++ )
					{
						String nameS = "";
						if ( bbsList[i][0][0].equals("회사") )
							nameS = "회사 " + bbsList[i][j][k].substring( 3 );
						else if ( bbsList[i][0][0].equals("동아리") )
							nameS = "동아리 " + bbsList[i][j][k].substring( 4 );
						else
							nameS = bbsList[i][j][k];
					
						if ( option != null && option.getFirstBoard().equals( bbsList[i][j][k] ) )
							out.println("<option value='" + bbsList[i][j][k] +"' selected> "+ nameS +" </option>");
						else
							out.println("<option value='" + bbsList[i][j][k] +"'> "+ nameS +" </option>");				
					}		// "k" end
				}		// "j" end
			}				
		}
							
		out.println("       </select>");
		out.println("    </td>");
		out.println("  </tr>");
			
		// 오늘 기준으로 며칠전까지 보여주나...
		out.println("  <tr>");
		out.println("    <td " + option1 + "><font size=2>&nbsp;&nbsp;기&nbsp;간?</font></td>");
		out.println("    <td " + option2 + "><input type=\"text\" name=\"period\" value=\"" );

		if ( option == null )
			out.println( 30  );
		else
			out.println( option.getPeriod()  );
			
		out.println( "\" size=\"5\"><font size=2 color=black>일</font>");
		out.println("    </td>");
		out.println("</tr>");

		// 화면당 몇개의 게시물을 보여줄것인가?
		out.println("  <tr>");
		out.println("    <td  " + option1 + "><font size=2>&nbsp;&nbsp;페이지당 게시물의 수?</font></td>");
		out.println("    <td  " + option2 + "><input type=\"text\" name=\"numOfItemsInPage\" value=\"" );
		
		if ( option == null )
			out.println( 10 );
		else 
			out.println( option.getNumOfItemsInPage() );
		out.println("\" size=\"5\"><font size=2 color=black>개</font>");
		out.println("    </td>");
		out.println("  </tr>");

		// 게시물의 정렬순서
		out.println("  <tr>");
		out.println("    <td  " + option1 + "><font size=2>&nbsp;&nbsp;정렬 순서는?</font></td>");
		out.println("    <td  " + option2 + ">");
		
		if ( option != null )
		{						
			out.println("      <input type=\"radio\" name=\"sortMethod\" value=\"asc\"");
			if ( option.getSortMethod().equals( "asc" ) )
				out.println("checked><font size=2 color=black> 오 름 </font>");
			else
				out.println("><font size=2 color=black> 오 름</font> ");
							
			out.println("      <input type=\"radio\" name=\"sortMethod\" value=\"desc\"");
			if( option.getSortMethod().equals( "desc" ) )
				out.println("checked> <font size=2 color=black>내 림</font> ");
			else
				out.println("><font size=2 color=black> 내 림</font>");		
		}
		else
		{
			out.println("      <input type=\"radio\" name=\"sortMethod\" value=\"asc\"> <font size=2 color=black>오 름 </font>");
			out.println("      <input type=\"radio\" name=\"sortMethod\" value=\"desc\" checked><font size=2 color=black> 내 림 </font>");
		}
		out.println("    </td>");
		out.println("  </tr>");
		
		//	 key word 검색조건을 받는곳...
			out.println("  <tr>");
			out.println("    <td " + option1 + "><font size=2>&nbsp;&nbsp;키워드 검색</font></td>");
			out.println("    <td " + option2 + "><br>");

			if ( option != null )
			{
				System.out.println(" key word start ");
				String word = null;
				if ( option.getAuthor().equals("null")  )
					out.println("      <font color=black face='굴림' size=2>&nbsp;&nbsp;성명</font> <input type='checkbox' name='author'   >   ");
				else
				{
					word = option.getAuthor();
					out.println("      <font color=black face='굴림' size=2>&nbsp;&nbsp;성명</font> <input type='checkbox' name='author'  checked>   ");
				}
				System.out.println(" author = " + option.getAuthor() );
					
				if ( option.getTitle().equals("null") )	
					out.println("      <font color=black face='굴림' size=2>&nbsp;&nbsp;제목</font> <input type='checkbox' name='title' > ");
				else
				{			
					word = option.getTitle();
					out.println("      <font color=black face='굴림' size=2>&nbsp;&nbsp;제목</font> <input type='checkbox' name='title'  checked> ");
				}				
				System.out.println("title = " + option.getTitle() );
	
				if ( option.getContent().equals("null") )	
					out.println("      <font color=black face='굴림' size=2>&nbsp;&nbsp;본문</font> <input type='checkbox' name='content' ><br><br>");
				else
				{
					word = option.getContent();
					out.println("      <font color=black face='굴림' size=2>&nbsp;&nbsp;본문</font> <input type='checkbox' name='content'  checked><br><br>");
				}
				System.out.println("content = " + option.getContent() );
				
				if ( word != null )
					out.println("	  <font color=black face='굴림' size=2>&nbsp;&nbsp;검색어 </font>  <input type='text' name='word' size=14 maxlength=20 value='"+word+"'>" );
				else
					out.println("	  <font color=black face='굴림' size=2>&nbsp;&nbsp;검색어 </font>  <input type='text' name='word' size=14 maxlength=20>");
			}
			else
			{	
				out.println("      <font color=black face='굴림' size=2>&nbsp;&nbsp;성명</font> <input type='checkbox' name='author' >   ");
				out.println("      <font color=black face='굴림' size=2>&nbsp;&nbsp;제목</font> <input type='checkbox' name='title' > ");
				out.println("      <font color=black face='굴림' size=2>&nbsp;&nbsp;본문</font> <input type='checkbox' name='content'><br><br>");
				out.println("	  <font color=black face='굴림' size=2>&nbsp;&nbsp;검색어 </font>  <input type='text' name='word' size=14 maxlength=20>");
			}
			
  			out.println("    </td>");
			out.println("  </tr>");
		
		out.println("</table>");

		out.println("<p align=center><hr width=500></p>");
		
		out.println("<p align=\"center\">");
		out.println("<input type=\"button\" value=\" 설 정 \" onClick='Check_Form( this.form );'>   ");
		out.println("<input type=\"reset\" value=\" 취 소 \">");
		out.println("</p>");
			
		// 되돌아가기를 만들어 놓도록 하지요... 

		out.println("</form>");			
			
		out.println("</body></html>");
		out.close();
	}
	
	/*----------------------------------------------------------------- */
	/**
	 [메소드이름]: doPost<br>
	 [기능]: 사용자가 Option을 설정하는 서블릿<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"));		
		
		out.println("<html><head><title>개인 정보</title></head>");
		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>");
		
			String firstBoard = req.getParameterValues("firstBoard")[0];
			firstBoard = new String ( firstBoard.getBytes("ISO-8859-1"), "EUC-KR");
			System.out.println( firstBoard );
									
			String periodString = req.getParameterValues("period")[0];
			periodString = new String ( periodString.getBytes("ISO-8859-1"), "EUC-KR");
			int period = Integer.parseInt( periodString );	
			System.out.println( periodString );

			String numString = req.getParameterValues("numOfItemsInPage")[0];
			numString = new String ( numString.getBytes("ISO-8859-1"), "EUC-KR");
			int num = Integer.parseInt ( numString );
			System.out.println ( num );
			
			String sortMethod = req.getParameterValues("sortMethod")[0];
			sortMethod = new String ( sortMethod.getBytes("ISO-8859-1"), "EUC-KR");
			System.out.println( sortMethod );

			String author = null ;
			if ( req.getParameter( "author" ) != null )
			{
				author = req.getParameter( "author" );
				author = new String ( author.getBytes("ISO-8859-1"), "EUC-KR");
			}
			System.out.println( author );
			
			String title = null ;			
			if ( req.getParameter( "title" ) !=null )
			{
				title = req.getParameterValues( "title" )[0];
				title = new String ( title.getBytes("ISO-8859-1"), "EUC-KR");
			}
			System.out.println( title );
			
			String content = null ;
			if ( req.getParameter( "content" ) != null )
			{
				content = req.getParameterValues( "content" )[0];
				content = new String ( content.getBytes("ISO-8859-1"), "EUC-KR");
			}
			System.out.println( content );

			OptionProperty option = new OptionProperty( sortMethod, firstBoard, period, num, title, author, content);
			System.out.println(" option property 설정합니다.");
			
			bbsResultStatus = bbsController.setPersonalOption( id, option );			
			System.out.println("option property를  D/B에 입력했습니다.");
			
			out.println("<br>");
			out.println("<br>");			

			if( bbsResultStatus.getResultStatus() == 0 )
			{
				out.println("<p align=center><b>" + name + "님의 정보를 등록하였습니다.</b><br><br>");
				out.println("<p align=center><b>초기 화면인 " + firstBoard + " 게시판으로 돌아갑니다.</b><br><br>");
				out.println("<a href=\"/servlet/BBSListServlet?boardName=" + firstBoard + "\"><image border=0 src=\"../image/BBS_back.gif\" alt='돌아가기'></A></p>");
			}
			else
			{
				out.println("<p align=center><b>" + name + "님의 정보가 등록되지 않았습니다. 다시 설정하여 주십시요.</b><br><br>");
				out.println("<a href=\"/servlet/BBSOptionPropertyServlet\"><image border=0 src=\"../image/BBS_back.gif\" alt='돌아가기'></A></p>");
			}

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