package net.oni2.aeinstaller.backend.oni;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.HashSet;

/**
 * @author Christian Illy
 */
public class PersistDat {
	private RandomAccessFile dat = null;

	/**
	 * Open the given persist.dat
	 * 
	 * @param dat
	 *            Path to persist.dat
	 */
	public PersistDat(File dat) {
		try {
			this.dat = new RandomAccessFile(dat, "rw");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @return Currently unlocked levels in persist.dat
	 */
	public HashSet<Integer> getUnlockedLevels() {
		HashSet<Integer> result = new HashSet<Integer>();
		if (dat != null) {
			try {
				dat.seek(8);
				for (int i = 0; i < 32; i++) {
					int val = dat.read();
					for (int j = 0; j < 8; j++) {
						if ((val & (1 << j)) > 0) {
							result.add(i * 8 + j);
						}
					}
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * @param unlock
	 *            Levels to be unlocked in persist.dat
	 */
	public void setUnlockedLevels(HashSet<Integer> unlock) {
		if (dat != null) {
			if (unlock != null) {
				try {
					dat.seek(8);
					for (int i = 0; i < 32; i++) {
						int val = 0;
						for (int j = 0; j < 8; j++) {
							if (unlock.contains(i * 8 + j))
								val |= 1 << j;
						}
						dat.write(val);
					}
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}
	}

	/**
	 * Close file
	 */
	public void close() {
		if (dat != null) {
			try {
				dat.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
