/* $Id: SavedLPCObject.java,v 1.1.1.1 1998/10/27 20:34:03 borg Exp $ */
/* Copyright (c) 1998 George Reese, All Rights Reserved */
package com.imaginary.mud;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.Serializable;
import java.util.Hashtable;

/**
 * Represents a saved LPC object.
 * <BR>
 * Last modified $Date: 1998/10/27 20:34:03 $
 * @version $Revision: 1.1.1.1 $
 * @author George Reese (borg@imaginary.com)
 */
public class SavedLPCObject implements Serializable {
    private Hashtable attributes = new Hashtable();
    private boolean   loaded     = false;
    private File      saveFile   = null;
    
    /**
     * Loads data from an LPC object's save file.
     * @param f the save file
     */
    public SavedLPCObject(File f) {
	super();
	saveFile = f;
	{
	    Thread t = new Thread() {
		public void run() {
		    loadAttributes();
		}
	    };

	    t.start();
	}
    }

    public boolean containsKey(String attr) {
	synchronized( this ) {
	    while( !loaded ) {
		try { wait(1500); }
		catch( InterruptedException e ) { }
	    }
	}
	return attributes.containsKey(attr);
    }
    
    public Object get(String attr) {
	synchronized( this ) {
	    while( !loaded ) {
		try { wait(1500); }
		catch( InterruptedException e ) { }
	    }
	}
	return attributes.get(attr);
    }
    
    private void loadAttributes() { 
	BufferedReader input;

	try {
	    input = new BufferedReader(new FileReader(saveFile));
	}
	catch( FileNotFoundException e ) {
	    synchronized( this ) {
		loaded = true;
	    }
	    return;
	}
	while( true ) {
	    LPCData data;
	    String line, nom;
	    int i;
	    
	    try {
		line = input.readLine();
		if( line == null ) {
		    try { input.close(); }
		    catch( IOException salt ) { }
		    break;
		}
	    }
	    catch( IOException e ) {
		try { input.close(); }
		catch( IOException salt ) { }
		break;
	    }
	    if( line.startsWith("#") ) {
		continue;
	    }
	    i = line.indexOf(" ");
	    if( i == -1 ) {
		continue;
	    }
	    nom = line.substring(0, i);
	    line = line.substring(i+1);
	    if( line.startsWith("(/") ) {
		continue;
	    }
	    try {
		data = new LPCData(line);
	    }
	    catch( LPCDataFormatException e ) {
		e.printStackTrace();
		try { input.close(); }
		catch( IOException salt ) { }
		break;
	    }
	    attributes.put(nom, data.getObject());
        }
	synchronized( this ) {
	    loaded = true;
	}
    }
}