package club.tmworks.io;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.json.Json;
import javax.json.JsonObject;
import javax.json.JsonReader;
import org.json.JSONObject;

/**
 *
 * @author MURAKAMI Takahiro <daianji@gmail.com>
 */
public class JsonIO {

    public static JsonObject loadJson(String loadFileName) {
        JsonObject rvalue = null;
        try {
            File f = new File(loadFileName);
            FileInputStream fis = new FileInputStream(f);
            InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
            BufferedReader br = new BufferedReader(isr);

            String jsonSrc = "";
            String line = "";
            while ((line = br.readLine()) != null) {
                jsonSrc += line;
            }

            JsonReader jsonReader = Json.createReader(new StringReader(jsonSrc));
            rvalue = jsonReader.readObject();
            return rvalue;
        } catch (FileNotFoundException ex) {
            Logger.getLogger(JsonIO.class.getName()).log(Level.SEVERE, null, ex);
        } catch (UnsupportedEncodingException ex) {
            Logger.getLogger(JsonIO.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(JsonIO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return rvalue;
    }

    public static void saveJsonFile(String fielFullPath, JsonObject src) {
        JSONObject jobj = new JSONObject(src.toString());
        String midStr = jobj.toString(4);

        String mediafilepath = fielFullPath;
        try (PrintWriter pw = new PrintWriter(
                new BufferedWriter(
                        new OutputStreamWriter(
                                new FileOutputStream(mediafilepath), "UTF-8")
                )
        )) {
            pw.print(midStr);
            pw.flush();
        } catch (UnsupportedEncodingException | FileNotFoundException ex) {
            Logger.getLogger(JsonIO.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public static String getString(JsonObject src) {
        JSONObject jobj = new JSONObject(src.toString());
        String midStr = jobj.toString(4);
        return midStr;
    }

}
