package com.Series40Book.midp.model.questions;

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

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

/**
 * To use the heap memory for question storage. This is for
 * devices that have extremely small RMS spaces (e.g., the 7210)
 */
public class QuestionsNavigatorRAM 
           extends QuestionsNavigator {

  private TriviaQuestion [] questions;

  protected QuestionsNavigatorRAM () 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 {

    questions = new TriviaQuestion [0];

    // 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();
      totalNum += size;
      int prevLength = questions.length;

      TriviaQuestion [] newSet = new TriviaQuestion[totalNum];
      for (int i = 0; i < prevLength; i++) {
        newSet[i] = questions[i];
      }
      questions = newSet;

      for (int i = prevLength; i < prevLength + size; i++) {
        worker.updateWaitStatus ("Downloading item " + i);

        TriviaQuestion question = new TriviaQuestion ();
        // Load the data from the HTTP stream
        question.load(hdin);
        questions[i] = question;
        answers.put(question.questionId, new Integer(-1));
      }

      resetSession ();

    } catch (Exception e) {
      e.printStackTrace();
      throw new Exception ("Download failed, connection error");
    } 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++;
    if (currentId <= questions.length) {
      // currentId starts from 1
      currentQuestion = questions[currentId - 1];
      return true;
    } else {
      return false;
    }
  }


}
