package com.Series40Book.midp.model.messaging;

import javax.wireless.messaging.*;
import javax.microedition.io.*;
import javax.microedition.rms.*;

/**
 * Created by IntelliJ IDEA.
 */
public class InboxImpl implements Inbox, MessageListener {

  static final String rmsName = "InboxStore";
  RecordStore inbox;
  RecordEnumeration re;
  private int currentID;

  public InboxImpl () {
  }

  public void setupListener (String port) throws Exception {
    MessageConnection sconn =
            (MessageConnection) Connector.open("sms://:" + port);
    sconn.setMessageListener (this);
  }

  public String firstMessage () throws Exception {
    inbox = RecordStore.openRecordStore(rmsName, true);
    re = inbox.enumerateRecords(null, null, true);
    return nextMessage();
  }

  public String nextMessage () throws Exception {
    if (re.hasNextElement()) {
      currentID = re.nextRecordId ();
      return new String(inbox.getRecord(currentID));
    } else {
      // Maybe the end has reached, loop back
      re.reset();
      if (re.hasNextElement()) {
        currentID = re.nextRecordId ();
        return new String (inbox.getRecord(currentID));
      } else {
        // No record in the enumeration
        return null;
      }
    }
  }

  public void deleteMessage () throws Exception {
    inbox.deleteRecord(currentID);
  }

  public void cleanUp () {
   try {
      if (re != null) {
        re.destroy();
      }
    } catch (Exception e) {
      // ignore all
    }

    try {
      if (inbox != null) {
        inbox.closeRecordStore();
      }
    } catch (Exception e) {
      // ignore all
    }
  }

  public void notifyIncomingMessage (MessageConnection c) {
    new Thread(new IncomingHandler(c)).start();
  }

}

class IncomingHandler implements Runnable {

  private MessageConnection sconn;

  public IncomingHandler (MessageConnection c) {
    sconn = c;
  }

  public synchronized void run () {
    try {
      Message msg = sconn.receive();
      if (msg instanceof TextMessage) {
        String msgText = ((TextMessage) msg).getPayloadText();
        RecordStore inbox =
                RecordStore.openRecordStore(InboxImpl.rmsName, true);
        inbox.addRecord(msgText.getBytes(), 0, msgText.length());
        inbox.closeRecordStore ();
      } else {
        // Discard non-text messages
      }
    } catch (Exception e) {
      e.printStackTrace ();
    }
  }
}
