package com.mot.labs.ucsl.util;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.Hashtable;

public class PropertiesFile extends Hashtable {
	
	protected PropertiesFile defaults = null;
	
	public PropertiesFile() {
		super();
	}
	
	public PropertiesFile(PropertiesFile defaults) {
		this.defaults = defaults;
	}
	
	public String getProperty(String key) {
		String val = (String)this.get(key);
		if (val == null && defaults != null) {
			val = (String)defaults.getProperty(key);
		}
		return val;
	}
	
	public String getProperty(String key, String defaultValue) {
		String val = getProperty(key);
		if (val == null) {
			val = defaultValue;
		}
		return val;
	}
	
	public void load(InputStream is) throws IOException {
		BufferedInputReader r = new BufferedInputReader(is);
		String line = null;
		while ((line = r.readLine()) != null) {
			System.out.println("Line:" + line);
			if (!(line.charAt(0) == '#')) {
				String key = line.substring(0,line.indexOf('='));
				String val = line.substring(line.indexOf('=')+1);
				this.put(key,val);
			}
		}
	}
	
	public void store(OutputStream os, String header) throws IOException {
		if (header != null) {
			os.write(("#" + header + "\n").getBytes());
		}
		os.write(("#" + (new Date(System.currentTimeMillis())).toString() + "\n").getBytes());
		Enumeration e = this.keys();
		while (e.hasMoreElements()) {
			String key = (String)e.nextElement();
			os.write((key + "=" + this.getProperty(key) + "\n").getBytes());
		}
	}
}
