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

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

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

public class BBSReadItemServlet 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 ;
		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"));		

		String boardname = req.getParameter("boardName");
		System.out.println( "boardName = " + boardname);

		String number = req.getParameter("number");
		int no = Integer.parseInt( number);
		System.out.println(" number = " + no );
		
		boolean in = false;
		String increase = req.getParameter("increase");
		if ( increase != null )
		{
			increase= new String( increase.getBytes("ISO-8859-1"), "EUC-KR");
			if ( increase.equals("true" ) )
				in = true;
		}
		System.out.println( " increase = " + in );

		Item item = bbsController.readItem(id, boardname, no, in);

		// 이전글, 다음글을 지정해주기 위해서 리스트를 가져오고, number를 읽어 온다.
		if(item.getNumber() != 0)
		{
			//해당 id에 맞는 option property를 가져와서 넘긴다.
			//어떤 게시판인지를 지정해줘야 합니다.
			OptionProperty option = bbsController.getPersonalOption( id );
			Item[] list = bbsController.listItem( boardname, option );
			int length = list.length;
			
			int next=0, forward=0;
			if ( length >= 2 )			{
				System.out.println( "next, forward ");
				for ( int i = 1; i < length ; i++)
				{
					if ( list[i].getNumber() == item.getNumber() )
					{
						if ( i > 1 ) forward = list[i-1].getNumber();
						if ( i < list.length-1 ) next = list[i+1].getNumber();
						break;
					}
				}
			}
			System.out.println("next, forward setting ");

			String BBSBoardName = item.getBBSBoardName();
			System.out.println( BBSBoardName );
			
			int Number = item.getNumber();
			System.out.println( Number );
			
			String Author = item.getAuthor();
			System.out.println( Author );
			
			String Email = item.getEmail();
			System.out.println( Email) ;
			
			String Title = item.getTitle();
			System.out.println( Title );
			
			String ItemType = item.getItemType();
			System.out.println( ItemType);
			
			String Content = item.writeContent();
			System.out.println( Content );
			
			String AttachedFile = item.getAttachedFile();
			System.out.println( "'" + AttachedFile + "'" );
			String[] fName = null;

			if ( !AttachedFile.equals(" ") )
			{
				int n = AttachedFile.charAt(0) - 48;
				fName =new String[n];
				int index = 0 ;
				for( int s=2, e=0; AttachedFile.length() > s ; )
				{
					e = AttachedFile.indexOf('/', s);
					String temp = AttachedFile.substring ( s, e);
					fName[ index ++ ] =  temp;
					s = e + 1 ;
				}
			}	
			
			String Date = item.getDate();
			int ViewCount = item.getViewCount();
			int Reference = item.getReference();
			int Lev = item.getLev();

			out.println("<html>");
			
			out.println("<head>");
			out.println("<title>글 읽기</title>");
			
			out.println("<script language=\"JavaScript\">");
			out.println("<!--");
			
			out.println("function Check_Delete()");
			out.println("{");
			out.println("	var answer = confirm('게시물을 삭제하시겠습니까?');");
			out.println("	if ( answer == true )");
			out.println("	{");
			out.println(" 	  if ( '"+  item.getAuthor() +"' == '" + name + "(" + id + ")' ) ");
			out.println(" 	     document.form1.submit();");
			out.println(" 	  else if ( '"+  kind +"' == 'manager' ) ");
			out.println(" 	     document.form1.submit();");			
			out.println(" 	  else");
			out.println(" 	     alert('작성자와 사용자가 일치하지 않습니다. \\n\\n작성자만이 삭제할수 있습니다.');");
			out.println("	}");
			out.println("	else");
			out.println("		alert('삭제가 취소되었습니다.');");
			out.println(" }");
			
			out.println("function modify()");
			out.println("{");			
			out.println("   if('"+  item.getAuthor() +"' == '" + name + "(" + id + ")' ) ");
			out.println("	{");
			out.println("      document.form2.submit();");
			out.println("	}");
			out.println("   else");
			out.println("      alert('작성자와 사용자가 일치하지 않습니다. \\n\\n작성자만이 수정할수 있습니다.');");
			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><br>");
			out.println("<hr width=500></p>");
					
			out.println("<table cellpadding=\"2\"  width=500 align=\"center\">");
			
			// 테이블의 첫열의 속성...
			String td = "<td width=200 bgcolor=\"#c7e4ff\" align=center><font size=2>";
			
			// 제목을 입력받는곳...			
			out.println("    <tr>");
			out.println("        " + td + "제 목</font></td>");
			out.println("        <td><font size=2>" + ItemType + Title  + "</font></td>");
			out.println("    </tr>");
			
			// 작성자를 입력받는곳...
			out.println("    <tr>");
			out.println("        " + td +"작 성 자</font></td>");
			out.println("        <td><font size=2>" + Author.substring(0, Author.indexOf("(") ) + "( "+Email+" )</font></td>");
			out.println("    </tr>");
			System.out.println(" author ok!");
	
			// 제일중요한 내용을 입력하는 곳
			out.println("    <tr>");
			out.println("        " + td +"내용</font></td>");
			out.println("        <td><font size=2>"+ Content +"</td></font>");
			out.println("    </tr>");
			System.out.println(" content ok!");
			
			//첨부파일?
			out.println("    <tr>");
			out.println("        " + td +"첨 부 파 일</font></td>");
			out.println("        <TD><font size=2>");
			if ( fName != null )
			{
				for ( int i = 0 ; i < fName.length; i++)
				{	
					out.println("           <a href=\"http://210.105.44.2/file/bbs/" + fName[i] + "\">"+ fName[i].substring ( fName[i].indexOf('-', 0)+1 ) +"</a><br>");
				}
			}
			else
			{
				out.println("첨부파일이 없습니다.");
			}
			out.println("        </font></TD>");
			out.println("    </tr>");
			System.out.println(" file attached ok!");		
			
			out.println("</table>");
			
			out.println("<br>");
			out.println("<hr width=500>");						
			out.println("<br>");			
	
			// 답변, 삭제, 수정, 이전글, 리스트보기, 다음글.....로 연결하는 테이블..		
			out.println("<table  align=\"center\" width=500>");
			out.println("  <tr>");
			out.println("    <td><a href='/servlet/BBSWriteServlet?number=" + Number
					+ "&boardName=" + boardname + "'><image src='../image/BBS_reply.gif' alt='답변' border=0></td>");
			out.println("    <form name='form1' method=\"post\" action='/servlet/BBSDeleteItemServlet'>");
			out.println("	<input type=hidden name='boardName' value='" + boardname +"'><input type=hidden name='number' value='" + Number +"'>");
			out.println("	<td><a onclick='Check_Delete();'><image src='../image/BBS_delete.gif' alt='삭제' border=0></a></td></form>");
						
			out.println("	<form name='form2' method='get' action='/servlet/BBSUpdatingItemServlet'>");
			out.println("<input type=hidden name='boardName' value='" + boardname+"'><input type=hidden name='number' value='" + Number +"'>");
			
			out.println("    <td><a onclick='modify();'><image src='../image/BBS_modify.gif' alt='수정' border=0></a></td></form>");
					
			if ( forward != 0 ) 
				out.println("    <td><a href=\"/servlet/BBSReadItemServlet?boardName=" + boardname
					+ "&number=" + forward + "&increase=true\"><image src='../image/BBS_back.gif' alt='이전글' border=0></a></td>");
			out.println("    <td><a href='/servlet/BBSListServlet?boardName="+ boardname + "'><image src='../image/BBS_list.gif' alt='리스트' border=0></a></td>");
			if ( next != 0 )
				out.println("    <td><a href=\"BBSReadItemServlet?boardName=" + boardname
					+ "&number=" + next +  "&increase=true\"><image src='../image/BBS_forward.gif' alt='다음글' border=0></a></td>");
			out.println("  </tr>");
			out.println("</table>");
		}
		else
		{
			out.println("<html>");
			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("<br>");		
			out.println("<br>");
			out.println("<p align=center>자료 읽기 권한이 없습니다.<br><br>");
			out.println("<a href='/servlet/BBSListServlet?boardName="+ boardname + "'><image src='../image/BBS_list.gif' alt='리스트' border=0></a></p>");

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