package com.Series40Book.midp.model;

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

/**
 * The preference store. We use singleton rather than static methods here
 * because we want to do some additional internal initialization in the
 * constructor method.
 */
public class PrefStore {

  public String category;
  public int googleResultsNum;
  public int googleTextMargin;
  public boolean googleIsPhrase;

  private String storeName = "Pref";

  private static PrefStore pref = new PrefStore ();

  private PrefStore () {
    try {
      restore ();
    } catch (Exception e) {
      setDefaults ();
    }
  }

  public static PrefStore getInstance () {
    return pref;
  }

  private void setDefaults () {
    category = "music02";
    googleResultsNum = 5;
    googleTextMargin = 100;
    googleIsPhrase = false;
  }


  public synchronized void save () throws Exception {
    RecordStore rs =
        RecordStore.openRecordStore(storeName, true);
    ByteArrayOutputStream bos =
        new ByteArrayOutputStream ();
    DataOutputStream dbos = new DataOutputStream (bos);
    dbos.writeUTF(category);
    dbos.writeInt(googleResultsNum);
    dbos.writeInt(googleTextMargin);
    dbos.writeBoolean(googleIsPhrase);

    byte [] buf = bos.toByteArray ();

    // If the record store is new, add a record.
    // If not, reset the first record.
    if (rs.getNumRecords() == 0) {
      rs.addRecord(buf, 0, buf.length);
    } else {
      rs.setRecord(1, buf, 0, buf.length);
    }

    dbos.close();
    bos.close();
    rs.closeRecordStore();
  }


  public synchronized void restore () throws Exception {
      RecordStore rs =
          RecordStore.openRecordStore(storeName, true);

      byte [] buf = rs.getRecord(1);
      ByteArrayInputStream bis =
          new ByteArrayInputStream (buf);
      DataInputStream dbis = new DataInputStream (bis);
      category = dbis.readUTF();
      googleResultsNum = dbis.readInt();
      googleTextMargin = dbis.readInt();
      googleIsPhrase = dbis.readBoolean();

      dbis.close();
      bis.close();
      rs.closeRecordStore();
  }

}