/*
	게시물을 작성할때
*/

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

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

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

public class BBSWriteServlet 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
	{      
		res.setContentType("text/html;charset=euc-kr");
		// 캐쉬를 못하도록..
		res.setHeader("cache-control", "no-cache");
		PrintWriter out =new PrintWriter(new OutputStreamWriter( res.getOutputStream(),"EUC-KR"));		
		
		// session 확인하는곳....		
		HttpSession session = req.getSession(true);
		
		boolean authentication = false ;
		String kind = null ;
		String id = null ;
		String name = null ;
		String department= null;
		String team = null;
		String mail = 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");
            mail = (String)session.getValue("Mail");
       }
       else {
            session.invalidate();
            res.sendRedirect("../Login.html");
       }
	   // session 확인 끝!!!	
		
		String boardname = req.getParameter("boardName");
		System.out.println( "boardName = " + boardname);
		
		String number = req.getParameter("number");
		
		out.println("<html>");
		
		out.println("<head>");
		out.println("<title>게시판 글 올리기</title>");
		
		out.println("<script language=\"JavaScript\">");
		out.println("<!--");
		
		// file attache 하는데 필요한 함수
		out.println("var AtthNum = 0;");
		out.println("function AppendAttachFile()");
		out.println("{");
		out.println("      	  var AtthBox=\"\";");
		out.println("          var AtthOk = true;");
		out.println("          if(AtthNum > 5)");
		out.println("          {");
		out.println("                 alert(\"더이상 파일을 첨부할 수 없습니다.\");");
		out.println("                 return;");
		out.println("          }");
		out.println("          if(AtthNum > 0)");
		out.println("          {");
		out.println("                 var file;AtthBox = \"document.forms[0].ATTH\"+(AtthNum-1);");
		out.println("                 AtthBox += \".value\";file = eval(AtthBox);");
		out.println("                 if(file.length <= 0 ) AtthOk = false;");
		out.println("          }");
		out.println("          if(AtthOk == true)");
		out.println("          {");
		out.println("                 var Atth= \"document.all.AtthBox\"+AtthNum;Atth += \".style.display = \";");
		out.println("                 Atth += \"(document.all.AtthBox\"+AtthNum;Atth += \".style.display == 'none') ? '':'none'\";");
		out.println("                 eval(Atth);");
		out.println("                 AtthNum++;");
		out.println("          }");
		out.println("}");
		
		// form을 전송하기 전에 적당한 데이타가 입력되었는지 체크하는곳
		out.println("function Check_Form(form)");
		out.println("{");
		out.println("     if(form.title.value.length == 0 ) alert(\"필수항목인 제목을 입력하여 주십시요.\");");
		out.println("     else if(form.email.value.length == 0) alert(\"필수항목인 메일을 입력하여 주십시요.\");");
		out.println("     else if(form.content.value.length == 0) alert(\"필수항목인 내용을 입력하여 주십시요.\");");
		out.println("     else form.submit();");
		out.println("}");
		
		out.println("function backClick()");
		out.println("{ ");
		out.println("    parent.frames['detail'].location=\"/servlet/BBSListServlet?boardName=" + boardname + "\"; ");
		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>");
		
		//글쓰기 타이틀....
		if ( number != null )
			out.println("<p align=\"center\"><font size=\"5\" color=\"darkblue\" face='돋움체'><b> 답  변  쓰  기 <b/></font><br>");
		else			
			out.println("<p align=\"center\"><font size=\"5\" color=\"darkblue\" face='돋움체'><b> 글  쓰  기 <b/></font><br>");

		out.println("<image src='../image/BBS_line.gif' width=600></p>");		
				
		//폼 태그 시작합니다...
		out.println("<form name=\"form1\" method=\"post\" action=\"/servlet/BBSWriteServlet\" enctype=\"multipart/form-data\">");

		Item item = null ;		
		String replyTitle = "", replyContent = "";

		if ( number != null )
		{
			int no = Integer.parseInt( number);
			System.out.println(" number = " + no );

			item = bbsController.readItem( id, boardname, no, false);
			
			out.println("<input type=\"hidden\" name=\"bbsboardName\" value=\""+ boardname+"\">");			
			out.println("<input type=\"hidden\" name=\"reference\" value=\"" + item.getReference() + "\">");
			out.println("<input type=\"hidden\" name=\"step\" value=\"" + item.getStep() + "\">");
			out.println("<input type=\"hidden\" name=\"lev\" value=\"" + item.getLev() + "\">");
			
			int start = item.getTitle().indexOf("[");
			if ( start == -1 ) start = 0;
			int end = item.getTitle().length();
			String e = item.getTitle().substring ( start , end);
			String h = item.getTitle().substring ( 0, start);
			String temp = h+"[답변]"+e;			
			replyTitle = " value=" + temp ;

			replyContent = item.getReply();	
		}
		else 
		{
			out.println("<input type=\"hidden\" name=\"bbsboardName\" value=\""+ boardname +"\">");
			out.println("<input type=\"hidden\" name=\"reference\" value=\"0\">");
			out.println("<input type=\"hidden\" name=\"step\" value=\"0\">");
			out.println("<input type=\"hidden\" name=\"lev\" value=\"0\">");
		}		
		
		String td = "<td width=200 bgcolor=\"#C7E4FF\" align=center><font size=2>";		// sell option
		
		out.println("<table cellpadding=\"2\" width=600 align=\"center\">");
		
		// 제목을 입력받는곳...
		out.println("    <tr>");
		out.println("        "+ td + "제 목</font></td>");
		out.println("        <td><input type=\"text\" name=\"title\" size=\"40\"" + replyTitle + "></td>");
		out.println("    </tr>");
		
		// 작성자를 입력받는곳...
		out.println("    <tr>");
		out.println("        "+ td +"작 성 자</font></td>");
		out.println("        <td><font size=2>"+ name + "( " + id + " )</font></td>");
		out.println("    </tr>");
		System.out.println(" author ok!");
		
		// 메일 주소
		out.println("    <tr>");
		out.println("        "+ td +"메 일</font></td>");
		out.println("        <td><input type=\"text\" name=\"email\" size=40 value="+id +"@"+mail+"></td>");
		out.println("    </tr>");
		System.out.println(" mail ok!");		

		// 종류는 일반, 긴급, 경조사가 있습니다. 선택하여 주십시요...
		out.println("    <tr>");
		out.println("        "+ td+"종 류</font></td>");
		out.println("        <td><select name=\"itemtype\">");
		out.println("            <option selected value=\"[일반]\">일   반</option>");
		out.println("            <option value=\"[긴급]\">긴   급</option>");
		out.println("            <option value=\"[경조사]\">경조사</option></select></td>");
		out.println("    </tr>");
		System.out.println(" item type ok!");		
		
		// 제일중요한 내용을 입력하는 곳
		out.println("    <tr>");
		out.println("        "+ td +"내용</font></td>");
		out.println("        <td><textarea name=\"content\" rows=\"10\" cols=\"60\">");
		out.println( replyContent );		
		out.println("</textarea></td>");
		out.println("    </tr>");
		System.out.println(" content ok!");
	
		//첨부파일?
		out.println("    <tr>");
		out.println("        "+ td +"첨 부 파 일</font></td>");
		out.println("        <TD><INPUT TYPE='BUTTON' VALUE='첨부추가' OnClick='AppendAttachFile()'>");
		out.println("        	<INPUT NAME='ATTH0' TYPE='FILE' SIZE=50 STYLE='display:none' ID='AtthBox0'>");
		out.println("            <INPUT NAME='ATTH1' TYPE='FILE' SIZE=50 STYLE='display:none' ID='AtthBox1'>");
		out.println("        	<INPUT NAME='ATTH2' TYPE='FILE' SIZE=50 STYLE='display:none' ID='AtthBox2'>");
		out.println("        	<INPUT NAME='ATTH3' TYPE='FILE' SIZE=50 STYLE='display:none' ID='AtthBox3'>");
		out.println("        	<INPUT NAME='ATTH4' TYPE='FILE' SIZE=50 STYLE='display:none' ID='AtthBox4'>");
		out.println("        </TD>");
		out.println("    </tr>");
		System.out.println(" file attached ok!");		
		
		out.println("</table>");
		out.println("<br>");
		out.println("<hr width=600>");
		
		out.println("<p align=\"center\">");
		out.println("<font size=2><input type=button onclick=\"Check_Form(this.form);\" value=' 확 인 '>   <input type=reset value= ' 취 소 '>   ");
		out.println("<input type=button value=' 돌아가기' onClick=\"backClick()\"></font>");		
		out.println("</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 ;
		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");          
            team = (String)session.getValue("Team");
       }
       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 bbsboardName="", author="";
		
		try 
		{
			ParseRequestData pD = new ParseRequestData(req.getInputStream());	
			
			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>");
			
				bbsboardName = pD.getParameter("bbsboardName");
				bbsboardName = new String( bbsboardName.getBytes("ISO-8859-1"), "EUC-KR");
				System.out.println("bbsboardName = " + bbsboardName +"OK!");
	
				int reference = 0;
				String referenceString = pD.getParameter("reference");
				if ( referenceString != null)
				{
					referenceString = new String ( referenceString.getBytes("ISO-8859-1"), "EUC-KR");
					reference = Integer.parseInt( referenceString );
				}
				System.out.println("reference( " + reference + " ) OK!");
	
				int step=0;
				String stepString = pD.getParameter("step");
				if ( stepString != null )
				{
					stepString = new String( stepString.getBytes("ISO-8859-1"), "EUC-KR");
					step = Integer.parseInt ( stepString );
				}
				System.out.println("step( " + step + ") OK!");
	
				int lev = 0;		
				String levString = pD.getParameter("lev");
				if ( levString != null)
				{
					levString = new String( levString.getBytes("ISO-8859-1"), "EUC-KR");			
					lev = Integer.parseInt( levString );
				}
				System.out.println("lev( " + lev +" ) OK!");
	
				String title = pD.getParameter("title");
				title = new String ( title.getBytes("ISO-8859-1"), "EUC-KR");
				System.out.println("title = " + title+"OK!");

				author = name + "(" + id + ")";
	
				String email = pD.getParameter("email");
				email = new String ( email.getBytes("ISO-8859-1"), "EUC-KR");
				System.out.println("email = " + email+"OK!");
	
				String itemType = pD.getParameter("itemtype");
				itemType = new String ( itemType.getBytes("ISO-8859-1"), "EUC-KR");
				System.out.println(" item type = " + itemType+"OK!");
	
							
				String content = pD.getParameter("content");
				content = new String ( content.getBytes("ISO-8859-1"), "EUC-KR");
				System.out.println("content OK!");
	
				//path = c:/groupware/bbsfile/	
				String filePath="c:/groupware/file/bbs";
				filePath = new String(filePath.getBytes("ISO-8859-1"),"KSC5601");
				
				Calendar fileDay = Calendar.getInstance();			
				String fileName = fileDay.get(Calendar.YEAR) +""+  (fileDay.get(Calendar.MONTH)+1) 
					+""+  fileDay.get(Calendar.DAY_OF_MONTH)+""+  fileDay.get(Calendar.HOUR_OF_DAY) 
					+""+  fileDay.get(Calendar.MINUTE) +""+  author;
					
	   			Vector attachedFiles = pD.getAttachedFileNames();
	   			
	   			// 파일이 몇개 첨부되는지하고, 파일의 이름들을 가져간다..
	   			String fName="";	
	     		if(!attachedFiles.isEmpty())
	     		{
	     			int i=0;
	        		for(; i<attachedFiles.size() ; i++)
	        		{        			
	         			pD.saveFile( (String)attachedFiles.elementAt(i), filePath, fileName);
	         			fName = fName + fileName +"-" + attachedFiles.elementAt(i)+"/";
	  	      		} 
	  	      		fName = i +"/" + fName;
	     		} 
		
				Calendar today = Calendar.getInstance();
				String date = today.get(Calendar.YEAR) + "/" + (today.get(Calendar.MONTH)+1) +"/" + today.get(Calendar.DAY_OF_MONTH);
				
				int viewCount = 0;
				System.out.println("view count OK!");
	
				Item item = new Item(team, bbsboardName, author, email, title, itemType, content, 
					fName, date, viewCount, reference, step, lev);
	
				bbsResultStatus = bbsController.addItem(item);
				
				System.out.println("item을 D/B에 입력합니다.");
				
				if(bbsResultStatus.getResultStatus() == 0 )
				{
					out.println("<p align=center><b>글이 등록되었습니다.</b><br>");
					out.println("<a href='/servlet/BBSListServlet?boardName="+ bbsboardName + "'><image src='../image/BBS_list.gif' alt='리스트보기' border=0></a></p>");
				}
				else
				{
					out.println("<p align=center><b>글이 등록되지 않았습니다.</b><br>");
					out.println("<a href='/servlet/BBSListServlet?boardName="+ bbsboardName + "'><image src='../image/BBS_list.gif' alt='리스트보기' border=0></a></p>");
				}
						
			}
			catch(Exception e)
			{
				System.out.println( e.toString() );
			}
			
		out.println("</body></html>");
		out.close();
	}
	
}