package com.koeping.lukas.sensordatacollector;

import android.os.AsyncTask;

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

public class EventMarker extends AsyncTask<EventInformation, Void, Boolean> {

    private final String SAVE_DIRECTORY = "SensorDataCollector";
    private final String EVENT_FILENAME = "Events.txt";
    private FileWriter fw = null;
    private BufferedWriter bw = null;
    private String directory_name;
    private long startTime;

    public EventMarker(String directory_name, long startTime) {
        this.directory_name = directory_name;
        this.startTime = startTime;
    }

    @Override
    protected void onPreExecute() {

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

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


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

        File eventFile = new File(directory, EVENT_FILENAME);

        try {
            fw = new FileWriter(eventFile, true);
            bw = new BufferedWriter(fw, 32768);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @Override
    protected Boolean doInBackground(EventInformation... info) {

        EventInformation ei = info[0];
        long time = ei.getTimestamp() - startTime;

        try {
            bw.write(time + ";" + ei.getEvent());
            bw.newLine();


            bw.flush();
            bw.close();

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

        return true;
    }




}
