package com.Series40Book;

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

public class CameraCanvas extends Canvas
               implements CommandListener {

  private Command capture;
  private Command skip;
  private Command exit;

  private Player player;
  private VideoControl video;

  public CameraCanvas () {

    capture = new Command ("Capture", Command.OK, 1);
    skip = new Command ("Skip", Command.CANCEL, 1);
    exit = new Command ("Exit", Command.EXIT, 0);
    addCommand (capture);
    addCommand (skip);
    addCommand (exit);
    setCommandListener (this);

    int width = getWidth();
    int height = getHeight();


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

      video =
    (VideoControl) player.getControl("VideoControl");
      video.initDisplayMode(
        VideoControl.USE_DIRECT_VIDEO, this);

      video.setDisplayLocation(2, 2);
      video.setDisplaySize(width - 4,
                           height - 4);

      player.start ();

    } catch (Exception e) {
      e.printStackTrace ();
    }
    video.setVisible(true);
  }

  public void paint(Graphics g) {
    int width = getWidth();
    int height = getHeight();

    // Draw a green border around the VideoControl.
    g.setColor(0x00ff00);
    g.drawRect(0, 0, width - 1, height - 1);
    g.drawRect(1, 1, width - 3, height - 3);
  }

  public void keyPressed(int keyCode) {
    int action = getGameAction(keyCode);
    if (action == FIRE) {
      capture ();
      BlogClient.showPhotoPreview ();
    }
  }

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

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

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

  private void capture () {
    try {
      // PNG, 160x120
      byte [] tmp = video.getSnapshot(null);
      BlogClient.photoPreview =
          BlogClient.createPreview(
              Image.createImage(tmp, 0, tmp.length));
      BlogClient.photoData = tmp;
      BlogClient.photoType = "jpg";

      /*
      BlogClient.photoData = video.getSnapshot(
          "encoding=jpeg&width=320&height=240");
      BlogClient.photoPreview = video.getSnapshot(
          "encoding=png&width=160&height=120");
      BlogClient.photoType = "jpg";
      */


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

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

}