package com.Series40Book;

import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
import javax.microedition.io.HttpConnection;
import javax.microedition.io.Connector;
import java.io.DataInputStream;
import java.io.DataOutputStream;


public class BlogClient extends MIDlet {

  public static Display display;
  private static BlogClient controller;

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

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

  static String url;
  public static byte [] photoData;
  public static Image photoPreview;
  public static byte [] audioData;
  public static String message;
  public static String photoType = "png";

  public BlogClient () {
    display = Display.getDisplay(this);
    controller = this;

    url = getAppProperty ("BlogServerURL");
  }

  protected void startApp () {
    initSession ();
    showCamera ();
  }

  protected void pauseApp () {
    // Do nothing
  }

  protected void destroyApp (boolean unconditional) {
    // Do nothing
  }

  public static void exit () {
    controller.destroyApp (true);
    controller.notifyDestroyed ();
  }

  public static void initSession () {
    photoData = null;
    audioData = null;
    message = null;
  }

  public static void showCamera () {
    CameraView camera = new CameraView ();
    // CameraCanvas camera = new CameraCanvas ();
    display.setCurrent (camera);
  }

  public static void showPhotoPreview () {
    PhotoPreview preview = new PhotoPreview ();
    display.setCurrent(preview);
  }

  public static void showAudioRecorder () {
    AudioRecorder recorder = new AudioRecorder ();
    display.setCurrent (recorder);
  }

  public static void showMessageForm () {
    MessageForm form = new MessageForm ();
    display.setCurrent (form);
  }

  public static void showAlert (String title,
                                String mesg) {
    Alert a = new Alert (title, mesg, null,
                         AlertType.ALARM);
    a.setTimeout(5000);
    display.setCurrent(a);
  }

  public static void submit () {

    String status = "No status";

    if (message == null || message.equals("")) {
      message = "No message";
    }

    HttpConnection conn = null;
    DataInputStream din = null;
    DataOutputStream dout = null;

    try {
      conn = (HttpConnection) Connector.open(url);
      conn.setRequestMethod(HttpConnection.POST);

      dout = conn.openDataOutputStream ();

      if (photoData == null && audioData == null) {
        dout.writeInt (NO_OBJECT);
        dout.writeUTF (message);

      } else if (photoData != null && audioData == null) {
        dout.writeInt (PHOTO_ONLY);
        dout.writeUTF (message);
        dout.writeUTF (photoType);
        dout.writeInt (photoData.length);
        dout.write (photoData, 0, photoData.length);

      } else if (photoData == null && audioData != null) {
        dout.writeInt (AUDIO_ONLY);
        dout.writeUTF (message);
        dout.writeInt (audioData.length);
        dout.write (audioData, 0, audioData.length);

      } else if (photoData != null && audioData != null) {
        dout.writeInt (PHOTO_AUDIO);
        dout.writeUTF (message);
        dout.writeUTF (photoType);
        dout.writeInt (photoData.length);
        dout.write (photoData, 0, photoData.length);
        dout.writeInt (audioData.length);
        dout.write (audioData, 0, audioData.length);
      }
      dout.flush ();
      dout.close ();

      din = conn.openDataInputStream();
      int respcode = din.readInt ();
      if (respcode == SUCCESS) {
        status = "Success!";
      } else if (respcode == FAILURE) {
        status = "Wrong opcode";
      } else {
        status = "Bad response " + respcode;
      }
      din.close ();

    } catch (Exception exp) {
      exp.printStackTrace ();
      status = "Failed operation " + exp.getMessage();

    } finally {
      try {
        if (dout != null) dout.close ();
        if (din != null) din.close();
        if (conn != null) conn.close();
      } catch (Exception exp) {}
    }

    Report report = new Report(status);
    display.setCurrent (report);
  }

  public static void startSubmit () {
    WaitScreen wait = new WaitScreen ();
    display.setCurrent(wait);
    
    Thread t = new SubmitWorker ();
    t.start ();
  }


  // Scale down the image by skipping pixels
  public static Image createPreview (Image image) {
    int sw = image.getWidth();
    int sh = image.getHeight();

    int pw = 160;
    int ph = pw * sh / sw;

    Image temp = Image.createImage(pw, ph);
    Graphics g = temp.getGraphics();

    for (int y = 0; y < ph; y++) {
      for (int x = 0; x < pw; x++) {
        g.setClip(x, y, 1, 1);
        int dx = x * sw / pw;
        int dy = y * sh / ph;
        g.drawImage(image, x - dx, y - dy,
            Graphics.LEFT | Graphics.TOP);
      }
    }

    Image preview = Image.createImage(temp);
    return preview;
  }

}