package zero1hd.polyjet.util;

import java.util.HashMap;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.files.FileHandle;
import com.badlogic.gdx.utils.Base64Coder;
import com.badlogic.gdx.utils.Json;

public class Base64Preferences {
	FileHandle base64File;
	HashMap<String, String> prefKeys;
	Json json;
	
	public Base64Preferences(String prefName) {
		base64File = Gdx.files.external(".prefs/.priv/" + prefName);
		json = new Json();
		
		flush();
	}
	
	public void putString(String key, String string) {
		prefKeys.put(key, string);
	}
	
	public void putObj(String key, Object object) {
		prefKeys.put(key, json.toJson(object));
	}
	
	public void writeBase64String(String text) {
		base64File.writeString(Base64Coder.encodeString(text), true);
	}
	
	public void writeBase64Object(Object obj) {
		base64File.writeString(Base64Coder.encodeString(json.toJson(obj)), true);
	}
	
	@SuppressWarnings("unchecked")
	public void flush() {
		prefKeys = json.fromJson(HashMap.class, new String(Base64Coder.decode(base64File.readString())));
		if (prefKeys == null) {
			prefKeys = new HashMap<>();
		}
		base64File.writeString(null, false);
		writeBase64Object(json);
	}
	
	
}
