package org.loklak.tools;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Collection;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONTokener;

/**
 * This extends JSONObject to be a file which gets loaded and written to disk
 *
 */
public class JSONFile extends JSONObject {
	
	private File file;

	public JSONFile(File file) throws IOException{
		super();
		this.file = file;
		if(this.file.exists()){
			JSONTokener tokener;
			tokener = new JSONTokener(new FileReader(file));
			putAll(new JSONObject(tokener));
		}
		else{
			this.file.createNewFile();
		}
	}
	
	private void writeFile() throws JSONException{
		FileWriter writer;
		try {
			writer = new FileWriter(file);
			writer.write(this.toString());
			writer.close();
		} catch (IOException e) {
			throw new JSONException(e.getMessage());
		}
	}

	@Override
	public JSONObject put(String key, boolean value) throws JSONException {
		this.put(key, value);
		writeFile();
		return this;
	}
	
	@Override
	public JSONObject put(String key, double value) throws JSONException {
		this.put(key, value);
		writeFile();
		return this;
	}
	
	@Override
	public JSONObject put(String key, Collection<?> value) throws JSONException {
		this.put(key, value);
		writeFile();
		return this;
	}
	
	@Override
	public JSONObject put(String key, int value) throws JSONException {
		this.put(key, value);
		writeFile();
		return this;
	}
	
	@Override
	public JSONObject put(String key, long value) throws JSONException {
		this.put(key, value);
		writeFile();
		return this;
	}
	
	@Override
	public JSONObject put(String key, Map<?, ?> value) throws JSONException {
		this.put(key, value);
		writeFile();
		return this;
	}
	
	@Override
	public JSONObject put(String key, Object value) throws JSONException {
		this.put(key, value);
		writeFile();
		return this;
	}
	
	@Override
	public Object remove(String key) {
		this.remove(key);
		writeFile();
		return this;
	}
}

@@ -1009,37 +1009,32 @@
 ONException %7B%0A%09%09
-this.
 put(key, value);
@@ -1026,32 +1026,32 @@
 ut(key, value);%0A
+
 %09%09writeFile();%0A%09
@@ -1146,37 +1146,32 @@
 ONException %7B%0A%09%09
-this.
 put(key, value);
@@ -1290,37 +1290,32 @@
 ONException %7B%0A%09%09
-this.
 put(key, value);
@@ -1424,37 +1424,32 @@
 ONException %7B%0A%09%09
-this.
 put(key, value);
@@ -1559,37 +1559,32 @@
 ONException %7B%0A%09%09
-this.
 put(key, value);
@@ -1699,37 +1699,32 @@
 ONException %7B%0A%09%09
-this.
 put(key, value);
@@ -1844,21 +1844,16 @@
 ion %7B%0A%09%09
-this.
 put(key,
@@ -1943,23 +1943,18 @@
  key) %7B%0A
+
 %09%09
-this.
 remove(k

Remove unnessecary code