package net.heartshield.signal;

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

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

/**
 * @author David Madl (git@abanbytes.eu)
 * @date 2017-04-21
 */
public class Series {
    public double[] t;
    public double[] x;

    public Series(double[] t, double[] x) {
        this.t = t;
        this.x = x;
    }

    public Series(String fileName) {
        try {
            load(fileName);
        } catch (JSONException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // note: Google Gson would be nicer, but since the code exists... why not use it.
    private void load(String fileName) throws JSONException, IOException {
        FileInputStream is;
        is = new FileInputStream(new File(fileName));
        String s = readFileContents(is);
        //System.out.println(s);
        JSONObject ppgSeries = new JSONObject(s);

        this.t = json2array(ppgSeries.getJSONArray("t"));
        this.x = json2array(ppgSeries.getJSONArray("x"));

        //System.out.println("t=" + DVec.toString(t));
        //System.out.println("x=" + DVec.toString(x));
    }

    private static double[] json2array(JSONArray array) throws JSONException {
        double[] res = new double[array.length()];
        for(int i = 0; i < res.length; i++)
            res[i] = array.getDouble(i);
        return res;
    }

    // to do: deduplicate (create helper class), see duplicate in AppData.java
    private static String readFileContents(FileInputStream is) throws IOException {
        BufferedReader buf = new BufferedReader(new InputStreamReader(is));
        String line = buf.readLine();
        StringBuilder sb = new StringBuilder();
        while (line != null) {
            sb.append(line).append("\n");
            line = buf.readLine();
        }
        return sb.toString();
    }
}
