/*
	게시물을 list 를 보여줄때....
*/

import java.io.*;
import java.util.*;

import javax.servlet.*;
import javax.servlet.http.*;

import com.etri.groupware.*;
import com.etri.groupware.bbs.*;

public class BBSListServlet extends HttpServlet
{
	GroupwareControllerInterface groupwareController=null;
	BBSControllerInterface bbsController = 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 ;
		String team = null;
		String department = 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");          
            team = (String)session.getValue("Team");
            department = (String)session.getValue("Department");
       }
       else {
            session.invalidate();
            res.sendRedirect("../Login.html");
       }
	   // session 확인 끝!!!		

		OptionProperty option=null;		// 개인의 option property
		SearchProperty so=null;			// 검색 property
		Item[] list=null;
		
		int pageCurrent=0;
		String boardName="", word="";

		//해당 id에 맞는 option property를 가져와서 넘긴다.
		//그런데 어떤 게시판인지를 지정해줘야 합니다.					
		option = bbsController.getPersonalOption( id );
			
		res.setContentType("text/html;charset=euc-kr");
		// 캐쉬를 못하도록..
		res.setHeader("cache-control", "no-cache");
		PrintWriter out =new PrintWriter(new OutputStreamWriter( res.getOutputStream(),"EUC-KR"));
		
		if ( option == null )
		{
			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>");

			out.println("<p align=center>"+ name + " 님의 게시판 Option이 설정되어 있지 않습니다.<br><br>");
			out.println( " 게시판 Option을 설정하여 주십시요.<br><br>");
			out.println("<a href=\"/servlet/BBSOptionPropertyServlet\">Option 설정하기</a><br></p>");
			out.println("</body></html>");
			out.close();
		}
		else			
		{			
			try
			{			
				String mode = req.getParameter("mode");
				if ( mode == null  )		mode = "list";		//기본 모드는 list 입니다.
				if ( mode.equals("search") )
				{	
					mode = new String ( mode.getBytes("ISO-8859-1"), "EUC-KR");
					System.out.println( mode + " mode 입니다.<br> ");
					
					boardName = req.getParameter("boardName");
					if ( boardName != null)
						boardName = new String( boardName.getBytes("ISO-8859-1"), "EUC-KR");
					System.out.println("게시판 이름 = " + boardName );
						
					String pageString = req.getParameter("page");
					if ( pageString != null )
					{
						pageString = new String ( pageString.getBytes("ISO-8859-1"), "EUC-KR");
						pageCurrent = Integer.parseInt( pageString );
					}
					else pageCurrent=1;
					System.out.println( "페이지 번호 = "+pageCurrent );
				
					// search는 모두 form 태그로 받는다... 
					word= req.getParameter("word");
					if ( word != null )
						word = new String ( word.getBytes("ISO-8859-1"), "EUC-KR");
					System.out.println(" 검색 단어는 " + word + " 입니다.");
		
					String author = req.getParameter("author");
					if( author != null )
					{
						author = new String ( author.getBytes("ISO-8859-1"), "EUC-KR");
						if ( author.equals("checked") )		author = word;				
						else author=null;
					}
					
					String title = req.getParameter("title");
					if ( title != null )
					{
						title = new String ( title.getBytes("ISO-8859-1"), "EUC-KR");
						if ( title.equals("checked") )		title = word;				
						else title=null;
					}
		
					String content = req.getParameter("content");
					if ( content != null )
					{
						content = new String ( content.getBytes("ISO-8859-1"), "EUC-KR");
						if ( content.equals("checked") )		content = word;				
						else content=null;
					}	
					
					so = new SearchProperty( title, author, content);					
					list = bbsController.searchItems( boardName, so, option);
				}
				else		
				{
					boardName = req.getParameter("boardName");
					System.out.println("게시판 이름 = " + boardName );
						
					String pageString = req.getParameter("page");
					if ( pageString != null )
						pageCurrent = Integer.parseInt( pageString );
					else pageCurrent = 1;	
					System.	out.println( "페이지 번호 = "+pageCurrent );
					
					list = bbsController.listItem( boardName, option );
					System.out.println( (list.length-1) + " 게시물을 가져왔습니다.<br>");
				}

			// 총 페이지수
			int length=0, pageTotal=0;
			if (list.length >= 2 )
			{
				length = list.length - 1;
				pageTotal = length/option.getNumOfItemsInPage() ;
				int temp = length%option.getNumOfItemsInPage() ;
				if ( temp > 0 )
					pageTotal++;
			}
			
			// 첫 게시물의 번호, 현재 페이지 번호를 받아 온다.
			int num = (pageCurrent-1) * option.getNumOfItemsInPage() +1;	
			
			
			// 키워드를 이용한 검색의 결과를 만드는 곳입니다... 			
			Item[] keywordList = null;
			
			if ( option.getTitle().equals("null") && option.getAuthor().equals("null") && option.getContent().equals("null") )
			{
				System.out.println("검색 기능이 지정되지 않았습니다.");				
			}
			else
			{
				String keywordTitle = null, keywordAuthor = null, keywordContent = null;
				if ( !option.getTitle().equals("null") )		keywordTitle = option.getTitle();
				if ( !option.getAuthor().equals("null") )		keywordAuthor = option.getAuthor();
				if ( !option.getContent().equals("null") )		keywordContent = option.getContent();
				
				SearchProperty keyword = 	new SearchProperty( keywordTitle, keywordAuthor, keywordContent );
				keywordList = bbsController.searchItems( boardName, keyword, option);
			}	
			
			// 개봉/미개봉 갯수 count
			int stateNo = 0;
			for ( int state=1; state < list.length; state++)
			{
				BBSResultStatus bbsResult = bbsController.checkDocumentOpen( id, list[state].getNumber() );
				if ( bbsResult.getResultStatus() != 0 )
					stateNo++;
			}
									
		
			out.println("<html><head><title> 게시판 </title></head>");		
			out.println("");
	
			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>" );
					
			int d = boardName.indexOf("부") + 1;
			int t = boardName.indexOf("팀") + 1;
			
			if ( boardName.substring( d, t).equals("팀") || boardName.substring( d, t).equals("회사팀") || boardName.substring( d, t).equals("동아리팀") )
				out.println( boardName.substring(0, t-1 ) + " " + boardName.substring( t ) );
			else			
				out.println( boardName.substring(d, t ) +" " + boardName.substring( t ) );

			out.println( " 게시판</b></font><br></p>");
	
			out.println("<table width=600 align=\"center\">");
			out.println("	<tr>");
			out.println("		<td colspan=2>");
			out.println("	   <p align=\"left\"><font size=2 color=blue face='굴림'>새로운 게시물 총 " + stateNo + " 개</font><br>");
			out.println("		</td>");
			out.println("	</tr>");
			out.println("   <tr>");		
			out.println("	<td>");
			
			if ( keywordList != null )
				out.println("	   <p align=\"left\"><font size=2 color=black face='굴림'>KeyWord 검색 결과 : Total = " + (keywordList.length -1)+ "</font><br>");
			else
				out.println("	   <p align=\"left\"><font size=2 color=black face='굴림'>KeyWord 검색 조건 없음</font><br>");
			
			out.println("	</td>");
			out.println("	<td>");
			out.println("       <p align=\"right\"><font size=2 color=black face='굴림'>Page="+pageCurrent+"/"+"Total="+ length+ "</font><br>");
			out.println("	</td>");
			out.println("   </tr>");
			out.println("</table>");	
			out.println("<hr width=600><br>");		
			out.println();
			
			// 테이블의 셀색상
			String font = "<font size=2 color=black>";
			
			out.println("<table cellpadding=\"2\" width=600  align=\"center\">");
			out.println("   <tr bgcolor=\"#C7E4FF\">");
			out.println("      <td align=\"center\" width=80>"+ font +"번   호</font></td>");
			out.println("      <td colspan=2 align=\"center\" width=250>"+ font +"제   목</font></td>");
			out.println("      <td align=\"center\" width=90>"+ font +"작성자</font></td>");
			out.println("      <td align=\"center\" width=90>"+ font +"작성일</font></td>");
			out.println("      <td align=\"center\" width=90>"+ font +"조회수</font></td>");
			out.println("   </tr>");
			out.println("");
			
			if ( length != 0 )
			{	
				//긴급일경우 빨간색 제목
				if ( length <= ( pageCurrent*option.getNumOfItemsInPage() ))
				{					
					for ( ; num <= length ; ++num)				
					{						
						String screenTitle =  "";
						if ( list[num].getLev() > 1 )
						{
							int j = ( list[num].getLev() - 1 ) * 2 ;
							for ( int i = 0 ; i < j ; i ++ )
								screenTitle = screenTitle + "&nbsp;";
						}			
						
						// 키워드 검색에 있는 게시물의 tuple 색깔을 바꾼다...
						String color="white"  ;
						if ( keywordList != null)
						{
							for ( int i = 1; i < keywordList.length ; i++)
								if ( keywordList[i].getNumber() == list[num].getNumber() )
								{
									color = "\"#F5F5F5\"";
									break;
								}
						}
						
						out.println("   <tr bgcolor=" + color + ">");
						out.println("      <td align=\"center\">"+ font + list[num].getNumber() +"</font></td>");

						// 개봉 미개봉 상태확인하여 표시하기...
						out.println("      <td align=\"center\" width=40>"+ font );						
						
						BBSResultStatus openClose= bbsController.checkDocumentOpen( id, list[num].getNumber() );
						if ( openClose.getResultStatus() == 0 )
							out.println("<img src='../image/BBS_open.gif' alt='개봉' border=0>");
						else
							out.println("<img src='../image/BBS_close.gif' alt='미개봉' border=0>");
						 out.println("</font></td>");
						 
						 String color2 = "black";
						 if ( list[num].getItemType().equals("[긴급]") )
						 	color2 = "red";
						
						out.println("      <td width=210 align=\"left\"><a href=\"/servlet/BBSReadItemServlet?boardName=" + boardName
							+ "&number=" + list[num].getNumber() +  "&increase=true\"><font size=2 color=" + color2 + ">" + screenTitle + list[num].getTitle()+"</font></a></td>");
						out.println("      <td align=\"center\">"+ font + list[num].getAuthor().substring( 0, list[num].getAuthor().indexOf("(") ) +"</font></td>");
						out.println("      <td align=\"center\">"+ font + list[num].getDate() +"</font></td>");
						out.println("      <td align=\"center\">"+ font + list[num].getViewCount() +"</font></td>");
						out.println("   </tr>");
						out.println();
					}
				}
				else
				{
					for ( ; num <= ( pageCurrent * option.getNumOfItemsInPage() ) ; ++num)
					{								
						String screenTitle =  "";
						if ( list[num].getLev() > 1 )
						{
							int j = ( list[num].getLev() - 1 ) * 2 ;
							for ( int i = 0 ; i < j ; i ++ )
								screenTitle = screenTitle + "&nbsp;";
						}
						
						// 키워드 검색에 있는 게시물의 tuple 색깔을 바꾼다...
						String color="white " ;
						if ( keywordList != null )
						{
							for ( int i = 1; i < keywordList.length ; i++)
								if ( keywordList[i].getNumber() == list[num].getNumber() )
								{
									color = "\"#F5F5F5\"";
									break;
								}
						}

						out.println("   <tr bgcolor=" + color + ">");
						out.println("      <td align=\"center\">"+ font + list[num].getNumber() +"</font></td>");
						
						// 개봉 미개봉 상태확인하여 표시하기...
						out.println("      <td align=\"center\" width=40>"+ font );					
						
						BBSResultStatus openClose = bbsController.checkDocumentOpen( id, list[num].getNumber() );
						if ( openClose.getResultStatus() == 0 )							
							out.println("<img src='../image/BBS_open.gif' alt='개봉' border=0>");
						else
							out.println("<img src='../image/BBS_close.gif' alt='미개봉' border=0>"); 							
						 out.println("</font></td>");
						
						// 편지 종류가 긴급일경우, 빨간 제목... 
						 String color2 = "black";
						 if ( list[num].getItemType().equals("[긴급]") )
						 	color2 = "red";						

						out.println("      <td width=210  align=\"left\"><a href=\"/servlet/BBSReadItemServlet?boardName=" + boardName
							+ "&number=" + list[num].getNumber() + "&increase=true\"><font size=2 color=" + color2 + ">"  + screenTitle  + list[num].getTitle()+"</font></a></td>");
						out.println("      <td align=\"center\">"+ font + list[num].getAuthor().substring( 0, list[num].getAuthor().indexOf("(") ) +"</font></td>");
						out.println("      <td align=\"center\">"+ font + list[num].getDate() +"</font></td>");
						out.println("      <td align=\"center\">"+ font + list[num].getViewCount() +"</font></td>");
						out.println("   </tr>");
						out.println();
					}
				}
			}
			out.println("</table>");
			
			out.println("<br>");	
			out.println( "<table width=600 align=\"center\">");
			out.println( "  <tr>");
			out.println("    <td align=left>");		
				
			// 앞 페이지로 넘어갈수 있도록		
			if( pageCurrent != 1)
			{	
				if ( mode.equals("list") )
				{
					out.println("    <a href=\"/servlet/BBSListServlet?mode=list&boardName="+ boardName
						+ "&page="+ (pageCurrent-1) + "\"><image src='../image/BBS_forward.gif' alt='앞페이지' border=0 ></a>");
				}
				else if( mode.equals("search") )
				{
					String title="", author="", content= "";
					if ( so.getTitle()== word) 
						title = " value='checked' ";
					if ( so.getAuthor() == word) 
						author = " value='checked' ";
					if ( so.getContent() == word) 
						content = " value='checked' ";
						
					out.println("   <form name='forward' method='get' action='/servlet/BBSListServlet'>");	
					out.println("    <input type='hidden' name='mode' value='search'>");
					out.println("    <input type='hidden' name='boardName' value='"+ boardName + "'>");
					out.println("    <input type='hidden' name='word' value='"+ word + "'>");
					out.println("    <input type='hidden' name='author' "+ author + ">");
					out.println("    <input type='hidden' name='title' "+ title + ">");
					out.println("    <input type='hidden' name='content' "+ content + ">");
					out.println("    <input type='hidden' name='page' value='"+ (pageCurrent-1) +"'>");
					out.println("    <a onclick='forward.submit()'><image src=\"../image/BBS_forward.gif\" alt=\"앞페이지\" border=0></a>");
					out.println("     </form>");
					
				}
			}
		        
			// 다음 페이지로 넘어갈수 있도록
			if ( pageCurrent != pageTotal && pageTotal != 0)
			{
				if ( mode.equals("list") )
				{
					out.println("    <a href=\"/servlet/BBSListServlet?mode=list&boardName="+ boardName + "&page="+ (pageCurrent+1) 
						 + "\"><image src=\"../image/BBS_back.gif\" alt=\"다음페이지\" border=0></a>");				
				}
				else if( mode.equals("search") )
				{
					String title="", author="", content= "";
					if ( so.getTitle() == word) 
						title = " value='checked' ";
					if ( so.getAuthor()  == word) 
						author = " value='checked' ";
					if ( so.getContent() == word) 
						content = " value='checked' ";
						
					out.println("   <form name='next' method='get' action='/servlet/BBSListServlet'>");	
					out.println("    <input type='hidden' name='mode' value='search'>");
					out.println("    <input type='hidden' name='boardName' value='"+ boardName + "'>");
					out.println("    <input type='hidden' name='word' value='"+ word + "'>");
					out.println("    <input type='hidden' name='author' "+ author + ">");
					out.println("    <input type='hidden' name='title' "+ title + ">");
					out.println("    <input type='hidden' name='content' "+ content + ">");
					out.println("    <input type='hidden' name='page' value='"+ (pageCurrent+1) +"'>");
					out.println("    <a onclick='next.submit()'><image src=\"../image/BBS_back.gif\" alt=\"다음페이지\" border=0></a>");
					out.println("     </form>");
					
				}
			}
			out.println("    </td>");
			
			// 총 페이지수...		
			out.println("    <td align=center>");		
			boolean con = false;
			for ( int i = 1 ; i <= pageTotal ; i++)
			{
				if ( mode.equals("list") )
				{
					out.println("    <a href=\"/servlet/BBSListServlet?mode=list&boardName="+ boardName + "&page="+ i 
						+ "\"><font size=2>[" + i + "]</font></a>");				
				}
				else if( mode.equals("search") )
				{
					String title="", author="", content= "";
					if ( so.getTitle() == word ) 
						title = " value='checked' ";
					if ( so.getAuthor() == word) 
						author = " value='checked' ";
					if ( so.getContent() == word ) 
						content = " value='checked' ";
						
					if ( i == 1)
					{
						out.println("   <form name='pageNo' method='get' action='/servlet/BBSListServlet'>");							
						out.println("    <input type='hidden' name='mode' value='search'>");
						out.println("    <input type='hidden' name='boardName' value='"+ boardName + "'>");
						out.println("    <input type='hidden' name='word' value='"+ word + "'>");
						out.println("    <input type='hidden' name='author' "+ author + ">");
						out.println("    <input type='hidden' name='title' "+ title + ">");
						out.println("    <input type='hidden' name='content' "+ content + ">");
						out.println("    <input type='hidden' name='page' >");
						con = true;
					}
					out.println("    <a onclick='pageNo.page.value="+i+";pageNo.submit()'><font size=2>[" + i + "]</font></a>");					
				}
			}
			if (con )out.println("     </form>");
			out.println("    </td>");
			
			//글쓰기
			out.println("    <td align=right>");
			out.println("    <a href=\"/servlet/BBSWriteServlet?boardName=" + boardName +"\"><image src=\"../image/BBS_write.gif\" alt=\"글쓰기\" border=0></a>");
			out.println("     </td>");		
			out.println("  </tr>");
			out.println("</table>");	
			
			out.println("<hr width=600>");
					
			out.println("   <form name='searchMode' method='get' action='/servlet/BBSListServlet'>");
			
			out.println("    <input type='hidden' name='boardName' value='"+ boardName + "'>");
			out.println("    <input type='hidden' name='mode' value='search'>");
			out.println("    <input type='hidden' name='page' value='1'>");
	
			out.println("    <table align='center' border=0 cellpadding=0 cellspacing=0 >");
			out.println("         <tr>");
			out.println("           <td align=right>");
			out.println("             <font color=black face='굴림' size=2>성명</font> <input type='checkbox' name='author' value='checked'");
			
			if ( mode.equals("search") && ( so.getAuthor() == word) )
			{
					out.println(" checked><br>");
			}
			else out.println("><br>");
			
			out.println("             <font color=black face='굴림' size=2>제목</font> <input type='checkbox' name='title' value='checked'");
			if ( mode.equals("search") && ( so.getTitle() == word ) )
			{
				out.println(" checked><br>");
			}
			else out.println("><br>");
			
			out.println("             <font color=black face='굴림' size=2>본문</font> <input type='checkbox' name='content' value='checked'");
			if( mode.equals("search") && (so.getContent() == word) )
			{
				out.println(" checked><br>");
			}
			else out.println("><br>");
			
			out.println("            </td>");
			out.println("            <td align=left>");
			out.println("            <input type='text' name='word' size=14 maxlength=20 ");
			
			if ( mode.equals("search")  )
			{
				out.println(" value='"+word+"'>");
			}
			else out.println(" >");		
			out.println("          </td>");
			
			out.println("          <td>" + font);
			out.println("             <input type='submit' value='검색'>");
			out.println("           </font></td>");
			out.println("         </tr>");
			out.println("     </table>");
			out.println("     </form>");
			out.println();
			
			out.println("</body></html>");
			
			}
			catch(Exception e)
			{
				out.println( e.toString() );
			}
			
			out.close();
		}

	}	
	
}