package com.koeping.lukas.sensordatacollector;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;


public class SensorDataWriter {
    private String separator;
    private final String APP_DIRECTORY = "SensorDataCollector";
    private HashMap<String, BufferedWriter> writerHashMap;


    public SensorDataWriter(String directory_name) {
        this.writerHashMap = new HashMap<String, BufferedWriter>();
        this.separator = ";";

        File root = null;
        try {
            root = Helper.getStorageRoot();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        File directory = new File(root, APP_DIRECTORY + "/" + directory_name);


        if (!directory.exists()) {
            directory.mkdirs();
        }

        for(String sensorName : Sensors.getAllNames()) {
            File sensorFile = new File(directory, sensorName+".csv");
            FileWriter fw = null;
            BufferedWriter bw = null;

            try {
                fw = new FileWriter(sensorFile);
                bw = new BufferedWriter(fw, 32768);
                writerHashMap.put(sensorName, bw);
                writeFileHeaders(sensorName);
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    private void writeFileHeaders(String sensorname) {
        BufferedWriter bw = writerHashMap.get(sensorname);

        try {
            if (sensorname.equals(Sensors.ROTATION_MATRIX.getName())) {
                bw.write("Timestamp;");
                for (int i = 0; i < 15; i++) {
                    bw.write("Rotation_"+i+";");
                }
                bw.write("Rotation_15");
                bw.newLine();
            }
            else {
                bw.write("Timestamp;X;Y;Z");
                bw.newLine();
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void writeDataToFile(Sensors sensor, long timestamp, float[] data) {
        BufferedWriter bw = writerHashMap.get(sensor.getName());

        try {

            bw.write(timestamp+this.separator);
            for (int i = 0; i < data.length - 1; i++) {
                bw.write(data[i] + this.separator);
            }
            //Last column does not need a seperator
            bw.write(""+data[data.length-1]);
            bw.newLine();


        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void closeWriters() {
        for (String sensorName : writerHashMap.keySet()) {
            try {
                writerHashMap.get(sensorName).flush();
                writerHashMap.get(sensorName).close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }


}




