package com.Series40Book.midp.model.questions;

import com.Series40Book.midp.controller.*;
import com.Series40Book.midp.model.OpCodes;

import javax.microedition.rms.*;
import javax.microedition.io.*;
import java.io.*;

/**
 * The pluggable implementation of the QuestionNavigator
 * class. This one uses RMS for questions. For phones that
 * do not support large RMS stores, a heap memory version
 * is available.
 */
public class QuestionsNavigatorRMS
          extends QuestionsNavigator {

  private static final String questionStoreName =
                                       "QuestionStore";
  private RecordStore questionStore;

  protected QuestionsNavigatorRMS () throws Exception {
    // Setup the currentQuestion
    currentQuestion = new TriviaQuestion ();

    initSession ();
  }

  // Called before we start a new session. It cleans
  // up all the persistent data from the last session.
  //
  // All record open, close and delete commands are here
  public void initSession () throws Exception {

    // Close the record store if it is open. Since the open/close
    // operations only happen inside this static method. We know
    // that the store can ony be opened once before (in the previous
    // init() method call). This guarantees that the store is closed
    // after the next block
    try {
      if (questionStore != null) {
        questionStore.closeRecordStore ();
      }
    } catch (Exception e) {
      e.printStackTrace ();
    }

    // Delete all old questions.
    try {
      RecordStore.deleteRecordStore(questionStoreName);
    } catch (Exception e) {
      // The exception will be thrown
      // if it is the first time we call init()
    }

    try {
      questionStore =
          RecordStore.openRecordStore(questionStoreName,
                                      true);
    } catch (Exception e) {
      e.printStackTrace ();
      throw new Exception("Cannot open record store!");
    }

    // Reset the total number of questions
    totalNum = 0;
    // setup answer related variables
    resetSession ();
  }


  public void download (String category,
             WorkerRunnable worker) throws Exception {

    HttpConnection conn = null;
    DataInputStream hdin = null;
    DataOutputStream hdout = null;

    try {
      conn = (HttpConnection) Connector.open( url );
      conn.setRequestMethod(HttpConnection.POST);
      hdout = conn.openDataOutputStream();
      hdout.writeInt(OpCodes.DOWNLOAD); // Submit opcode
      hdout.writeUTF(category);
      hdout.flush();

      hdin = conn.openDataInputStream();
      int size = hdin.readInt();
      TriviaQuestion question = new TriviaQuestion ();
      for (int i = 0; i < size; i++) {
        worker.updateWaitStatus ("Downloading item " + i);

        // Load the data from the HTTP stream
        question.load(hdin);
        byte [] entry = question.persist();
        questionStore.addRecord(entry, 0, entry.length);

        answers.put(question.questionId, new Integer(-1));
      }

      resetSession ();

      totalNum += size;

    } catch (Exception e) {
      e.printStackTrace();
      throw new Exception ("Download failed");
    } finally {
      try {
        if (conn != null) conn.close();
        if (hdout != null) hdout.close();
        if (hdin != null) hdin.close();
      } catch (Exception e) {}
    }
  }

  // Move to the next question.
  // return true if there is more question
  public boolean next () {
    currentId++;
    try {
      if (currentId <= questionStore.getNumRecords()) {
        currentQuestion.load(
            questionStore.getRecord(currentId));
        return true;
      } else {
        return false;
      }
    } catch (Exception e) {
      e.printStackTrace ();
      return false;
    }
  }


}
