import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

/*
 *大岩研究会第6回サブゼミ
 *オリジナルレシピ投稿掲示板プログラム
 *レシピ一覧サーブレット
 */
public class IchiranServlet extends HttpServlet {
  
  //レシピを保存するファイルのパス
  private String recipeFilePath = "C:/WebTechs/tomcat4.0.1/webapps/okusama2/text/recipes.txt";
  
  /**
   * レシピ一覧のHTMLを出力する
   * (一覧には、HTTP GETメソッドを用いる)
   */
  public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {    
    
    //*****閲覧者がログインしているか調べる*****

    HttpSession session = request.getSession(false);//セッションの取得

    //ログインしていなかった場合、エラーページを生成する
    if(session == null){
		System.out.println("done");
      createErrorPage(response);
      return;//ここで、メソッドを終了する
    }    
    

    //*****レシピ一覧を出力する*****
    
    //HTML出力の準備をする
    response.setContentType("text/html;charset=Shift_JIS"); //文字化け防止
    PrintWriter out = response.getWriter(); //HTMLを出力するためのPrintWriterを作成する

    //ページの頭部分のHTMLを出力する
    out.println("<html>");
    out.println("<head><title>奥様Web ： 全レシピ</title></head>");
    out.println("<body bgcolor=\"#33CCFF\" text=\"#000000\">");
    out.println("<center><font size=5><b>おくさまWeb</b></font></center>");
    out.println("<hr>");
    
    //レシピ一覧をファイルから読み込む
    BufferedReader reader =
      new BufferedReader(new FileReader(recipeFilePath)); //ファイルを読み込むストリームを作成する
    while(true) {
      //contributor, title, date, content の順で読み込む
      String contributor = reader.readLine();
      if( contributor == null ) { //読み込めなかったらファイルの終わりなので、無限ループをぬける
        break;
      }
      String title = reader.readLine();
      String date = reader.readLine();
      String content = reader.readLine();
      
      //レシピのHTMLを出力する
      out.println("<p><b><font color=blue size=4>"+contributor+"</font>さんオリジナル</b></p>");
      out.println("<p><font size=5>「"+title+"」のレシピ</font></p>");
      out.println("(投稿時刻："+ date + ")<br>");
      out.println("<p>" + content + "</p>");
      out.println("<hr>");
    }
    reader.close(); //ストリームを閉じる
    
    //ページの尻尾部分のHTMLを出力する
    out.println("</body>");
    out.println("</html>");
    
    //HTML出力のあとかたづけをする
    out.close();
  }

  /**
   *閲覧者がログインしていなかった場合の処理
   */
  public void createErrorPage(HttpServletResponse response)throws IOException{
    //HTML出力の準備をする
    response.setContentType("text/html;charset=Shift_JIS"); //文字化け防止
    PrintWriter out = response.getWriter(); //HTMLを出力するためのPrintWriterを作成する

    out.println("<html>");
    out.println("<head>");
    out.println("<title>奥様Web-再ログイン</title>");
    out.println("</head>");
    out.println("<body bgcolor=\"#33CCFF\">");
    out.println("<h1>再ログインしてください</h1>");
    out.println("<p><a href=\"../html/login.html\">ログインページへ</a></p>");
    out.println("</body>");
    out.println("</html>");
  }
}
