package fun;

import javax.microedition.rms.*;

import java.util.*;

public class T3Library {

	public static Vector getIDs(){
		Vector v = new Vector();
		
		try {
			RecordStore rs = openRS();
			
			RecordFilter filter = new RecordFilter(){
				public boolean matches(byte[] buf){
					return true;
				}
			};
			
			RecordEnumeration re = rs.enumerateRecords(filter, null, false);	
			while(re.hasNextElement()){
				v.addElement(new Integer(re.nextRecordId()));
			}
		} catch(RecordStoreException rse){
			throw new RuntimeException(rse.toString());
		}
		
		return v;
	}

	public static T3Puzzle load(int id){
		try {
			RecordStore rs = openRS();
			
			byte[] buf = rs.getRecord(id);
			
			if(buf == null){
				return null;
			} else {
				return new T3Puzzle(id, buf);
			}
		} catch(RecordStoreException rse){
		}
		
		return null;
	}

	public static void save(T3Puzzle p){
		try {
			RecordStore rs = openRS();
			
			int id = p.getId();
			byte[] buf = p.getBoard();
			
			if(id <= 0){
				rs.addRecord(buf, 0, buf.length);
			} else {
				rs.setRecord(id, buf, 0, buf.length);
			}
		} catch(RecordStoreException rse){
		}
	}

	private static RecordStore openRS() throws RecordStoreException {
		return RecordStore.openRecordStore("T3", true);
	}
}