package tools;

import java.io.*;
import java.util.*;

public class Config {
  static RandomAccessFile configFile;

  // line 1: "odometer= <value>"
  static long odometer;    // total distance travelled in centimeters
  // line 2: "power= <value>"
  static long power;       // total time on (milliseconds)
  
  public static void initialize() {
    try { configFile = new RandomAccessFile("nomad.cfg", "rw"); }
    catch(FileNotFoundException e) {
      error("File not found: nomad.cfg");
      System.exit(-1);
    }

    StringTokenizer temp = getNext();
    String s = "not set...";
    if (temp == null || !(s = temp.nextToken()).equals("odometer=")) {
      // System.err.println("--nextToken() = ("+s+")");
      error("missing element in config file (odometer)");
    } else odometer = Long.parseLong(temp.nextToken());
    
    temp = getNext();
    if (temp == null || !(s = temp.nextToken()).equals("power=")) {
      // System.err.println("--nextToken() ("+s+")");
      error("missing element in config file (time on)");
    } else power = Long.parseLong(temp.nextToken());
  }
  
  private Config() {}               // defeat instantiation

  private static StringTokenizer getNext() {
    StringTokenizer st;
    String result;

    try {
      if ((result = configFile.readLine()) != null) {
	return (st = new StringTokenizer(result));
      }
    } catch (IOException e) {
      error("I/O Exception");
      e.printStackTrace();
    }
    return null;                    // end of stream reached
  }

  private static void error(String message) {
    System.err.println("ERROR: "+message);
  }

  public synchronized static void setOdometer(long dist) {
    // add old distance to new displacement
    odometer += dist;

    // update file
    update();
  }
  
  public synchronized static void setPower(long time) {
    // add old time to new time
    power += time;

    // update file
    update();
  }
  
  public synchronized static long getOdometer() {
    return odometer;
  }

  public synchronized static long getPower() {
    return power;
  }

  private synchronized static void update() {
    try {
      configFile.seek(0);           // return to start of file
      configFile.writeBytes("odometer= "+odometer+"\n");
      configFile.writeBytes("power= "+power+"\n");
    } catch (IOException e) {
      error("I/O Exception");
      e.printStackTrace();
    }
  }
}
