package com.Series40Book.BlogServer;

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

public class BlogServlet extends HttpServlet {

  private static int NO_OBJECT = 0;
  private static int PHOTO_ONLY = 1;
  private static int AUDIO_ONLY = 2;
  private static int PHOTO_AUDIO = 3;

  private static int SUCCESS = 1;
  private static int FAILURE = 2;

  private static String fileroot = null;
  private static String webroot = null;

  public void init() throws ServletException {
    InputStream in =
        getClass().getResourceAsStream("/conf.prop");
    Properties prop = new Properties ();
    try {
      prop.load (in);
      fileroot = prop.getProperty("Fileroot");
      webroot = prop.getProperty("Webroot");
    } catch (Exception e) {
      e.printStackTrace ();
      fileroot =
"/Users/juntao/Java/tomcat/jakarta-tomcat-4.1.24/webapps/BlogServer/content/";
      webroot = "/BlogServer/content/";
    }

  }

  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
             throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println(readTextFile("header.html"));
    out.println(readTextFile("entries.html"));
    out.println(readTextFile("footer.html"));

    out.flush ();
    out.close ();
  }

  public void doPost(HttpServletRequest request,
                     HttpServletResponse response)
              throws ServletException, IOException {

    response.setContentType("application/binary");

    InputStream in = request.getInputStream();
    OutputStream out = response.getOutputStream();
    DataInputStream din = new DataInputStream(in);
    DataOutputStream dout = new DataOutputStream(out);

    String current =
        Long.toString((new Date()).getTime());
    String body = "<b>Posted at</b>: " + 
        (new Date()).toString() + "<br/>";
    String filename;

    // Get the opcode
    int opcode = din.readInt();
    // Get the message body
    body += din.readUTF();
    body += "<br/>";

    if (opcode == NO_OBJECT) {
      // Save the message body
      saveMessage (body);
      dout.writeInt(SUCCESS);

    } else if (opcode == PHOTO_ONLY) {
      // Get photo data
      String photoType = din.readUTF ();
      byte [] photoData = receiveObject (din);

      // Save the photo data
      filename = current + "." + photoType;
      saveObject (photoData, filename);
      body = body + photoHtml(filename);

      // Save the message body
      saveMessage (body);
      dout.writeInt(SUCCESS);

    } else if (opcode == AUDIO_ONLY) {
      // Get the audio data
      byte [] audioData = receiveObject (din);

      // Save the audio data in a file
      filename = current + ".wav";
      saveObject (audioData, filename);
      body = body + audioHtml(filename);

      // Save the message body
      saveMessage (body);
      dout.writeInt(SUCCESS);

    } else if (opcode == PHOTO_AUDIO) {
      // Get the photo data
      String photoType = din.readUTF ();
      byte [] photoData = receiveObject (din);
      // Get the audio data
      byte [] audioData = receiveObject (din);

      // Save the photo data in a file
      filename = current + "." + photoType;
      saveObject (photoData, filename);
      body = body + photoHtml(filename);

      // Save the audio data in a file
      filename = current + ".wav";
      saveObject (audioData, filename);
      body = body + audioHtml(filename);

      // Save the message body
      saveMessage (body);
      dout.writeInt(SUCCESS);

    } else {
      dout.writeInt(FAILURE);
    }
    dout.flush();
    dout.close();
    din.close();
    in.close();
    out.close();
  }

  private byte [] receiveObject (DataInputStream din)
                                  throws IOException {
    int length = din.readInt();
    byte [] buf = new byte [length];
    din.readFully (buf);
    return buf;
  }

  private void saveObject (byte [] data, String name)
                                   throws IOException {
    FileOutputStream fout =
        new FileOutputStream(fileroot + name);
    fout.write(data, 0, data.length);
    fout.flush ();
    fout.close ();
  }

  private void saveMessage (String body)
                        throws IOException {
    body = body + "<hr/>";

    FileWriter writer =
      new FileWriter (fileroot + "entries.html", true);
    writer.write(body, 0, body.length());
    writer.flush ();
    writer.close ();
  }

  private String photoHtml (String filename) {
    return "<img src=\"" + webroot + filename +
           "\"/>" + "<br/>";
  }
  
  private String audioHtml (String filename) {
    return "<a href=\"" + webroot + filename +
      "\">" + "Audio file (wav format)</a>" + "<br/>";
  }
  
  
  private String readTextFile (String name)
                         throws IOException {
//    FileInputStream fin =
//        new FileInputStream(fileroot + name);
//    ByteArrayOutputStream baos =
//                       new ByteArrayOutputStream ();
//    byte [] buf = new byte [256];
//    int i = 0;
//    while ( (i = fin.read(buf)) != -1 ) {
//      baos.write(buf, 0, i);
//    }
//    baos.flush();
//    byte [] result = baos.toByteArray();
//    baos.close();
//    fin.close();
//    return result;

    StringBuffer result = new StringBuffer ();
    FileReader reader =
       new FileReader (fileroot + name);

    char [] buf = new char [256];
    int i = 0;
    while ( (i = reader.read(buf)) != -1 ) {
      result.append(buf, 0, i);
    }
    reader.close();
    return result.toString ();
  }
}

