aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/export/FieldNotes.java
blob: fdc6210bba3d403c0315568a7cb6acea1c946b98 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package cgeo.geocaching.export;

import cgeo.geocaching.Geocache;
import cgeo.geocaching.LogEntry;
import cgeo.geocaching.files.LocalStorage;
import cgeo.geocaching.utils.FileUtils;
import cgeo.geocaching.utils.SynchronizedDateFormat;

import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

/**
 * Field Notes are simple plain text files, but poorly documented. Syntax:<br>
 * <code>GCxxxxx,yyyy-mm-ddThh:mm:ssZ,Found it,"logtext"</code>
 */
class FieldNotes {

    private static final SynchronizedDateFormat FIELD_NOTE_DATE_FORMAT = new SynchronizedDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", TimeZone.getTimeZone("UTC"), Locale.US);

    private int size = 0;
    private final StringBuilder buffer = new StringBuilder();

    void add(final Geocache cache, final LogEntry log) {
        size++;
        buffer.append(cache.getGeocode())
                .append(',')
                .append(FIELD_NOTE_DATE_FORMAT.format(new Date(log.date)))
                .append(',')
                .append(StringUtils.capitalize(log.type.type))
                .append(",\"")
                .append(StringUtils.replaceChars(log.log, '"', '\''))
                .append("\"\n");
    }

    public String getContent() {
        return buffer.toString();
    }

    File writeToDirectory(final File exportLocation) {
        if (!LocalStorage.isExternalStorageAvailable()) {
            return null;
        }

        FileUtils.mkdirs(exportLocation);

        final SimpleDateFormat fileNameDateFormat = new SimpleDateFormat("yyyyMMddHHmmss", Locale.US);
        final File exportFile = new File(exportLocation.toString() + '/' + fileNameDateFormat.format(new Date()) + ".txt");

        if (!FileUtils.writeFileUTF16(exportFile, getContent())) {
            return null;
        }

        return exportFile;
    }

    public int size() {
        return size;
    }

}