package com.github.pocmo.sensordashboard.ui;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.github.pocmo.sensordashboard.R;
import com.github.pocmo.sensordashboard.database.DataEntry;

import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

import io.realm.Realm;
import io.realm.RealmResults;

public class ExportActivity extends Activity {
    private Realm mRealm;

    @Override
    protected void onCreate(final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_export);

        Button exportButton = (Button) findViewById(R.id.exportButton);
        exportButton.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(final View v) {
                        final Handler handler = new Handler();  //Optional. Define as a variable in your activity.

                        Runnable r = new Runnable() {
                            @Override
                            public void run() {
                                // your code here
                                handler.post(new Runnable() {
                                    public void run() {
                                        exportFile();
                                    }
                                });
                            }
                        };

                        Thread t = new Thread(r);
                        t.start();
                    }
                }

        );

        Button deleteButton = (Button) findViewById(R.id.deleteButton);
        deleteButton.setOnClickListener(
                new View.OnClickListener() {
                    @Override
                    public void onClick(final View v) {
                        deleteData();
                    }
                }
        );
    }

    private void deleteData() {
        mRealm = Realm.getInstance(this);
        mRealm.beginTransaction();

        RealmResults<DataEntry> result = mRealm.where(DataEntry.class).findAll();
        Log.e("SensorDashboard", "rows after delete = " + result.size());

        // Delete all matches
        result.clear();

        mRealm.commitTransaction();

        result = mRealm.where(DataEntry.class).findAll();
        Log.e("SensorDashboard", "rows after delete = " + result.size());
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void exportFile() {
        mRealm = Realm.getInstance(this);

        RealmResults<DataEntry> result = mRealm.where(DataEntry.class).findAll();
        final int total_row = result.size();
        final int total_col = 8;
        Log.e("SensorDashboard", "total_row = " + total_row);
        final String fileprefix = "export";
        final String date = new SimpleDateFormat("yyyyMMdd-HHmmss").format(new Date());
        final String filename = String.format("%s_%s.txt", fileprefix, date);

        final String directory = Environment.getExternalStorageDirectory().getAbsolutePath() + "/SensorDashboard";

        final File logfile = new File(directory, filename);
        final File logPath = logfile.getParentFile();

        if (!logPath.isDirectory() && !logPath.mkdirs()) {
            Log.e("SensorDashbaord", "Could not create directory for log files");
        }

        try {
            FileWriter filewriter = new FileWriter(logfile);

            String TestString = "";

            FileOutputStream fOut = openFileOutput(filename, MODE_WORLD_READABLE);

            OutputStreamWriter osw = new OutputStreamWriter(fOut);

            // Write the string to the file
            for (int i = 1; i < total_row; i++) {

                TestString += result.get(i).getAndroidDevice().toString();
                TestString += " ,";
                TestString += String.valueOf(result.get(i).getTimestamp());
                TestString += " ,";
                TestString += String.valueOf(result.get(i).getX());
                TestString += " ,";
                TestString += String.valueOf(result.get(i).getY());
                TestString += " ,";
                TestString += String.valueOf(result.get(i).getZ());
                TestString += " ,";
                TestString += String.valueOf(result.get(i).getAccuracy());
                TestString += " ,";
                TestString += String.valueOf(result.get(i).getDatasource());
                TestString += " ,";
                TestString += String.valueOf(result.get(i).getDatatype());
                TestString += "\n";
            }
            filewriter.write(TestString);
            filewriter.flush();
            filewriter.close();
            Log.e("SensorDashbaord", "export finished!");
        } catch (IOException ioe) {
            Log.e("SensorDashbaord", "IOException while writing Logfile");
        }
    }
}

@@ -338,16 +338,47 @@
 Entry;%0A%0A
+import java.io.BufferedWriter;%0A
 import j
@@ -570,16 +570,41 @@
 il.Date;
+%0Aimport java.util.Locale;
 %0A%0Aimport
@@ -3214,16 +3214,37 @@
 -HHmmss%22
+, Locale.getDefault()
 ).format
@@ -3790,25 +3790,24 @@
 r(logfile);%0A
-%0A
             
@@ -3810,182 +3810,95 @@
     
-String TestString = %22%22;%0A%0A            FileOutputStream fOut = openFileOutput(filename, MODE_WORLD_READABLE);%0A%0A            OutputStreamWriter osw = new OutputStreamWriter(fOut)
+BufferedWriter bw = new BufferedWriter(filewriter);%0A%0A            String TestString = %22%22
 ;%0A%0A 
@@ -3990,17 +3990,16 @@
  i++) %7B%0A
-%0A
         
@@ -4017,17 +4017,16 @@
 tString 
-+
 = result
@@ -4875,32 +4875,14 @@
     
-%7D%0A            filewriter
+    bw
 .wri
@@ -4909,26 +4909,32 @@
         
-filewriter
+%7D%0A            bw
 .flush()
@@ -4947,26 +4947,18 @@
         
-filewriter
+bw
 .close()

optimize file export