package com.Series40Book;

import javax.microedition.lcdui.*;
import javax.microedition.midlet.*;
import javax.microedition.rms.*;
import java.io.IOException;

public class PhotoViewer extends MIDlet {

  private static Display display;
  private static Search search;
  private static EditSlide editslide;
  private static ListSlides listslides;
  private static ShowSlide showslide;
  private static PhotoViewer controller;

  private static ImageAttribute current;
  private static int currentId;

  private static RecordStore imageAttrStore;
  private static RecordEnumeration imageAttrEnum;
  private static RecordComparator ratingComp;

  boolean exitConfirmed;

  public PhotoViewer () {
    display = Display.getDisplay (this);
    controller = this;
    ratingComp = new RatingComparator ();
  }

  protected void startApp () {
    exitConfirmed = false;

    try {
      imageAttrStore =
          RecordStore.openRecordStore("Attr", true);
      if (imageAttrStore.getNumRecords() == 0) {
        initRMS ();
      }
    } catch (Exception e) {
      e.printStackTrace();
      notifyDestroyed ();
    }

    try {
      imageAttrEnum =
              imageAttrStore.enumerateRecords(null,
                                  ratingComp, false);
    } catch (Exception e) {
      e.printStackTrace();
    }

    showList ();
  }

  protected void pauseApp () {
    // Do nothing
  }

  protected void destroyApp (boolean unconditional)
                  throws MIDletStateChangeException {
    if (!unconditional) {
      if (!exitConfirmed) {
        throw new MIDletStateChangeException ();
      }
    } else {
      try {
        imageAttrStore.closeRecordStore ();
      } catch (Exception e) {
        e.printStackTrace ();
      }
    }
  }

  public static void safeShutdown () {
    try {
      controller.destroyApp (false);
      controller.notifyDestroyed ();
    } catch (MIDletStateChangeException me) {
      display.setCurrent(
              new ConfirmExitScreen(controller));
    }
  }

  private void initRMS () throws Exception {
    int numOfImages = Integer.parseInt(
         controller.getAppProperty("NumberOfImages"));

    for (int i = 0; i < numOfImages; i++) {
      int tmpi = i + 1;
      String tmp =
           controller.getAppProperty("Image-" + tmpi);
      int cIdx = tmp.indexOf(",");
      ImageAttribute attr = new ImageAttribute (
                 tmp.substring(0, cIdx).trim());
      attr.title = tmp.substring(cIdx+1).trim();

      byte [] record = attr.serialize ();
      imageAttrStore.addRecord(record, 0, record.length);
    }
  }


  public static void backtoList () {
    display.setCurrent (listslides);
  }

  public static void doEdit (String comment,
                     int rating, boolean showComment) {
    current.comment = comment;
    current.rating = rating;
    current.showComment = showComment;

    try {
      byte [] record = current.serialize ();
      imageAttrStore.setRecord (currentId,
                        record, 0, record.length);
    } catch (Exception e) {
      e.printStackTrace();
    }

    showSlide ();
  }

  public static void next () throws Exception {

    if (!imageAttrEnum.hasNextElement ()) {
      imageAttrEnum.reset ();
    }

    currentId = imageAttrEnum.nextRecordId ();
    current = ImageAttribute.deserialize(
         imageAttrStore.getRecord(currentId));

    showSlide ();
  }

  public static void jumpTo (int index)
                         throws Exception {

    imageAttrEnum.reset ();
    for (int i = 0; i <= index; i++) {
      currentId = imageAttrEnum.nextRecordId () ;
    }
    current = ImageAttribute.deserialize(
         imageAttrStore.getRecord(currentId));

    showSlide ();
  }

  public static void showSearch () {
    search = new Search ();
    display.setCurrent (search);
  }

  public static void doSearch (String s) {

    SearchFilter searchFilter = new SearchFilter (s);
    try {
      imageAttrEnum =
         imageAttrStore.enumerateRecords(searchFilter,
                                    ratingComp, false);
    } catch (Exception e) {
      e.printStackTrace ();
    }

    showList ();
  }

  public static void showList () {
    String [] titles = null;
    try {
      int n = imageAttrEnum.numRecords();
      titles = new String [n];
      for (int i = 0; i < n; i++) {
        current = ImageAttribute.deserialize (
                        imageAttrEnum.nextRecord());
        titles[i] = current.title;
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

    listslides = new ListSlides (titles);
    display.setCurrent (listslides);
  }

  public static void showEdit () {
    editslide =
       new EditSlide (current.comment, current.rating);
    display.setCurrent (editslide);
  }

  public static void showSlide () {

    Image img = null;
    try {
      img = Image.createImage("/" + current.fileName);
    } catch (IOException e) {
      e.printStackTrace();
    }

    if (current.showComment) {
      showslide = new ShowSlide (img, current.title,
                     current.comment, current.rating);
    } else {
      showslide = new ShowSlide (img, current.title);
    }
    display.setCurrent (showslide);
  }

}