package com.Series40Book;

import javax.microedition.lcdui.*;
import javax.microedition.media.*;
import javax.microedition.media.control.*;


public class CameraView extends Form
          implements CommandListener {

  private Command capture;
  private Command skip;

  private Player player = null;
  private VideoControl video = null;

  public CameraView () {
    super ("Take a picture");

    showCamera ();

    capture = new Command ("Capture", Command.OK, 1);
    skip = new Command ("Skip", Command.CANCEL, 1);
    addCommand (capture);
    addCommand (skip);
    setCommandListener (this);
  }

  public void commandAction (Command c, Displayable d) {
    if (c == capture) {
      capture ();
      BlogClient.showPhotoPreview ();

    } else if (c == skip) {
      player.close ();
      BlogClient.showAudioRecorder ();

    }
  }

  private void showCamera () {
    try {
      player = Manager.createPlayer("capture://video");
      player.realize();

      // Add the video playback window (item)
      video = (VideoControl) player.getControl(
                                 "VideoControl");
      Item item = (Item) video.initDisplayMode(
          GUIControl.USE_GUI_PRIMITIVE, null);
      item.setLayout(Item.LAYOUT_CENTER |
                     Item.LAYOUT_NEWLINE_AFTER);
      append (item);
      // Add a caption
      StringItem s = new StringItem ("", "View finder");
      s.setLayout(Item.LAYOUT_CENTER);
      append (s);

      player.start();

    } catch (Exception e) {
      e.printStackTrace ();
    }
  }

  private void capture () {
    try {
      // PNG, 160x120
      // BlogClient.photoData = video.getSnapshot(null);
      //      OR
      // BlogClient.photoData = video.getSnapshot(
      //     "encoding=png&width=160&height=120");

      // BlogClient.photoPreview = BlogClient.photoData;
      // BlogClient.photoType = "png";

      byte [] tmp = video.getSnapshot(
          "encoding=jpeg&width=320&height=240");
      BlogClient.photoPreview =
          BlogClient.createPreview(
              Image.createImage(tmp, 0, tmp.length));
      BlogClient.photoData = tmp;
      BlogClient.photoType = "jpg";

      player.stop ();
      player.close ();

    } catch (Exception e) {
      e.printStackTrace ();
      BlogClient.showAlert ("Error", e.getMessage ());
    }
  }

}
