package org.faudroids.boxclub.settings;

import android.content.Context;

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

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class SettingsFileHandler {

    final Context context;
    FileOutputStream outputStream = null;
    FileInputStream inputStream = null;

    static final String SETTINGS_FILE_NAME = "boxclub_settings.json";


    public SettingsFileHandler(Context context) {
        this.context = context;
    }


    public void saveSettings(JSONObject settings) throws IOException {
        outputStream = context.openFileOutput(SETTINGS_FILE_NAME, Context.MODE_PRIVATE);
        outputStream.write(settings.toString().getBytes());
        outputStream.close();
    }


    public JSONObject loadSettings() throws IOException, JSONException {
        inputStream = context.openFileInput(SETTINGS_FILE_NAME);
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();

        String jsonInput;
        while((jsonInput = bufferedReader.readLine()) != null) {
            stringBuilder.append(jsonInput + "\n");
        }

        String result = stringBuilder.toString();
        inputStream.close();

        return new JSONObject(result);
    }
}
