package com.platypii.baseline.tracks;

import android.content.Context;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.util.Log;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Manage track files on the device.
 * Files are saved in either the external files dir, or the internal files.
 * Unsynced track files are stored in the top level directory.
 * Synced track files are moved to the "synced" directory.
 */
public class TrackFiles {
    private static final String TAG = "TrackFiles";

    private static final String syncedDirectoryName = "synced";

    public static synchronized List<TrackFile> getTracks(@NonNull Context context) {
        final List<TrackFile> jumps = new ArrayList<>();
        // Load jumps from disk
        final File logDir = getTrackDirectory(context);
        if(logDir != null) {
            final File[] files = logDir.listFiles();
            for (File file : files) {
                if(!file.getName().equals(syncedDirectoryName)) {
                    jumps.add(new TrackFile(file));
                }
            }
            // Sort by date descending
            Collections.sort(jumps, new Comparator<TrackFile>() {
                @Override
                public int compare(TrackFile track1, TrackFile track2) {
                    return -track1.getDate().compareTo(track2.getDate());
                }
            });
            return jumps;
        } else {
            Log.e(TAG, "Track storage directory not available");
            return jumps;
        }
    }

    public static File getTrackDirectory(@NonNull Context context) {
        final String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return context.getExternalFilesDir(null);
        } else {
            Log.w(TAG, "External storage directory not available, falling back to internal storage");
            return context.getFilesDir();
        }
    }

}

@@ -622,73 +622,8 @@
 %22;%0A%0A
-    private static final String syncedDirectoryName = %22synced%22;%0A%0A
     
@@ -733,20 +733,21 @@
 ckFile%3E 
-jump
+track
 s = new 
@@ -989,53 +989,200 @@
     
-if(!file.getName().equals(syncedDirectoryName
+final String filename = file.getName();%0A                // Tracks look like %22track_(yyyy-MM-dd_HH-mm-ss).csv.gz%22%0A                if(filename.startsWith(%22track_%22) && filename.endsWith(%22.csv.gz%22
 )) %7B
@@ -1202,20 +1202,21 @@
         
-jump
+track
 s.add(ne
@@ -1335,20 +1335,21 @@
 ns.sort(
-jump
+track
 s, new C
@@ -1510,19 +1510,19 @@
 ack1.get
-Dat
+Nam
 e().comp
@@ -1541,11 +1541,11 @@
 .get
-Dat
+Nam
 e())
@@ -1591,36 +1591,37 @@
          return 
-jump
+track
 s;%0A        %7D els
@@ -1708,20 +1708,21 @@
  return 
-jump
+track
 s;%0A     

Fix errors when non-track files were in storage dir