aboutsummaryrefslogtreecommitdiffstats
path: root/main/src/cgeo/geocaching/Geocache.java
blob: c2edf4446d3d5002f9c3c85c665bdc2450a0d1fd (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
package cgeo.geocaching;

import cgeo.geocaching.DataStore.StorageLocation;
import cgeo.geocaching.activity.ActivityMixin;
import cgeo.geocaching.activity.SimpleWebviewActivity;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.connector.IConnector;
import cgeo.geocaching.connector.ILoggingManager;
import cgeo.geocaching.connector.capability.ISearchByCenter;
import cgeo.geocaching.connector.capability.ISearchByGeocode;
import cgeo.geocaching.connector.gc.GCConnector;
import cgeo.geocaching.connector.gc.GCConstants;
import cgeo.geocaching.connector.gc.Tile;
import cgeo.geocaching.connector.gc.UncertainProperty;
import cgeo.geocaching.enumerations.CacheSize;
import cgeo.geocaching.enumerations.CacheType;
import cgeo.geocaching.enumerations.LoadFlags;
import cgeo.geocaching.enumerations.LoadFlags.RemoveFlag;
import cgeo.geocaching.enumerations.LoadFlags.SaveFlag;
import cgeo.geocaching.enumerations.LogType;
import cgeo.geocaching.enumerations.WaypointType;
import cgeo.geocaching.files.GPXParser;
import cgeo.geocaching.list.StoredList;
import cgeo.geocaching.location.Geopoint;
import cgeo.geocaching.network.HtmlImage;
import cgeo.geocaching.settings.Settings;
import cgeo.geocaching.utils.CalendarUtils;
import cgeo.geocaching.utils.CancellableHandler;
import cgeo.geocaching.utils.ImageUtils;
import cgeo.geocaching.utils.LazyInitializedList;
import cgeo.geocaching.utils.Log;
import cgeo.geocaching.utils.LogTemplateProvider;
import cgeo.geocaching.utils.LogTemplateProvider.LogContext;
import cgeo.geocaching.utils.MatcherWrapper;
import cgeo.geocaching.utils.RxUtils;

import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;

import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.BooleanUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.Nullable;

import rx.Scheduler;
import rx.Subscription;
import rx.functions.Action0;
import rx.schedulers.Schedulers;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.Parcelable;
import android.text.Html;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.EnumMap;
import java.util.EnumSet;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;

/**
 * Internal representation of a "cache"
 */
public class Geocache implements IWaypoint {

    private static final int OWN_WP_PREFIX_OFFSET = 17;
    private long updated = 0;
    private long detailedUpdate = 0;
    private long visitedDate = 0;
    private int listId = StoredList.TEMPORARY_LIST.id;
    private boolean detailed = false;

    @NonNull
    private String geocode = "";
    private String cacheId = "";
    private String guid = "";
    private UncertainProperty<CacheType> cacheType = new UncertainProperty<>(CacheType.UNKNOWN, Tile.ZOOMLEVEL_MIN - 1);
    private String name = "";
    private String ownerDisplayName = "";
    private String ownerUserId = "";
    private Date hidden = null;
    /**
     * lazy initialized
     */
    private String hint = null;
    @NonNull private CacheSize size = CacheSize.UNKNOWN;
    private float difficulty = 0;
    private float terrain = 0;
    private Float direction = null;
    private Float distance = null;
    /**
     * lazy initialized
     */
    private String location = null;
    private UncertainProperty<Geopoint> coords = new UncertainProperty<>(null);
    private boolean reliableLatLon = false;
    private String personalNote = null;
    /**
     * lazy initialized
     */
    private String shortdesc = null;
    /**
     * lazy initialized
     */
    private String description = null;
    private Boolean disabled = null;
    private Boolean archived = null;
    private Boolean premiumMembersOnly = null;
    private Boolean found = null;
    private Boolean favorite = null;
    private Boolean onWatchlist = null;
    private Boolean logOffline = null;
    private int favoritePoints = 0;
    private float rating = 0; // valid ratings are larger than zero
    private int votes = 0;
    private float myVote = 0; // valid ratings are larger than zero
    private int inventoryItems = 0;
    private final LazyInitializedList<String> attributes = new LazyInitializedList<String>() {
        @Override
        public List<String> call() {
            return inDatabase() ? DataStore.loadAttributes(geocode) : new LinkedList<String>();
        }
    };
    private final LazyInitializedList<Waypoint> waypoints = new LazyInitializedList<Waypoint>() {
        @Override
        public List<Waypoint> call() {
            return inDatabase() ? DataStore.loadWaypoints(geocode) : new LinkedList<Waypoint>();
        }
    };
    private List<Image> spoilers = null;

    private List<Trackable> inventory = null;
    private Map<LogType, Integer> logCounts = new EnumMap<>(LogType.class);
    private boolean userModifiedCoords = false;
    // temporary values
    private boolean statusChecked = false;
    private String directionImg = "";
    private String nameForSorting;
    private final EnumSet<StorageLocation> storageLocation = EnumSet.of(StorageLocation.HEAP);
    private boolean finalDefined = false;
    private boolean logPasswordRequired = false;

    private static final Pattern NUMBER_PATTERN = Pattern.compile("\\d+");

    private Handler changeNotificationHandler = null;

    /**
     * Create a new cache. To be used everywhere except for the GPX parser
     */
    public Geocache() {
        // empty
    }

    /**
     * Cache constructor to be used by the GPX parser only. This constructor explicitly sets several members to empty
     * lists.
     *
     * @param gpxParser ignored parameter allowing to select this constructor
     */
    public Geocache(final GPXParser gpxParser) {
        setReliableLatLon(true);
        setAttributes(Collections.<String> emptyList());
        setWaypoints(Collections.<Waypoint> emptyList(), false);
    }

    public void setChangeNotificationHandler(final Handler newNotificationHandler) {
        changeNotificationHandler = newNotificationHandler;
    }

    /**
     * Sends a change notification to interested parties
     */
    private void notifyChange() {
        if (changeNotificationHandler != null) {
            changeNotificationHandler.sendEmptyMessage(0);
        }
    }

    /**
     * Gather missing information for new Geocache object from the stored Geocache object.
     * This is called in the new Geocache parsed from website to set information not yet
     * parsed.
     *
     * @param other
     *            the other version, or null if non-existent
     * @return true if this cache is "equal" to the other version
     */
    public boolean gatherMissingFrom(final Geocache other) {
        if (other == null) {
            return false;
        }
        if (other == this) {
            return true;
        }

        updated = System.currentTimeMillis();
        // if parsed cache is not yet detailed and stored is, the information of
        // the parsed cache will be overwritten
        if (!detailed && other.detailed) {
            detailed = true;
            detailedUpdate = other.detailedUpdate;
            // boolean values must be enumerated here. Other types are assigned outside this if-statement
            reliableLatLon = other.reliableLatLon;
            finalDefined = other.finalDefined;
        }

        if (premiumMembersOnly == null) {
            premiumMembersOnly = other.premiumMembersOnly;
        }
        if (found == null) {
            found = other.found;
        }
        if (disabled == null) {
            disabled = other.disabled;
        }
        if (favorite == null) {
            favorite = other.favorite;
        }
        if (archived == null) {
            archived = other.archived;
        }
        if (onWatchlist == null) {
            onWatchlist = other.onWatchlist;
        }
        if (logOffline == null) {
            logOffline = other.logOffline;
        }
        if (visitedDate == 0) {
            visitedDate = other.visitedDate;
        }
        if (listId == StoredList.TEMPORARY_LIST.id) {
            listId = other.listId;
        }
        if (StringUtils.isBlank(geocode)) {
            geocode = other.geocode;
        }
        if (StringUtils.isBlank(cacheId)) {
            cacheId = other.cacheId;
        }
        if (StringUtils.isBlank(guid)) {
            guid = other.guid;
        }
        cacheType = UncertainProperty.getMergedProperty(cacheType, other.cacheType);
        if (StringUtils.isBlank(name)) {
            name = other.name;
        }
        if (StringUtils.isBlank(ownerDisplayName)) {
            ownerDisplayName = other.ownerDisplayName;
        }
        if (StringUtils.isBlank(ownerUserId)) {
            ownerUserId = other.ownerUserId;
        }
        if (hidden == null) {
            hidden = other.hidden;
        }
        if (!detailed && StringUtils.isBlank(getHint())) {
            hint = other.getHint();
        }
        if (size == CacheSize.UNKNOWN) {
            size = other.size;
        }
        if (difficulty == 0) {
            difficulty = other.difficulty;
        }
        if (terrain == 0) {
            terrain = other.terrain;
        }
        if (direction == null) {
            direction = other.direction;
        }
        if (distance == null) {
            distance = other.distance;
        }
        if (StringUtils.isBlank(getLocation())) {
            location = other.getLocation();
        }
        coords = UncertainProperty.getMergedProperty(coords, other.coords);
        // don't use StringUtils.isBlank here. Otherwise we cannot recognize a note which was deleted on GC
        if (personalNote == null) {
            personalNote = other.personalNote;
        } else if (other.personalNote != null && !personalNote.equals(other.personalNote)) {
            final PersonalNote myNote = new PersonalNote(this);
            final PersonalNote otherNote = new PersonalNote(other);
            final PersonalNote mergedNote = myNote.mergeWith(otherNote);
            personalNote = mergedNote.toString();
        }
        if (!detailed && StringUtils.isBlank(getShortDescription())) {
            shortdesc = other.getShortDescription();
        }
        if (StringUtils.isBlank(getDescription())) {
            description = other.getDescription();
        }
        // FIXME: this makes no sense to favor this over the other. 0 should not be a special case here as it is
        // in the range of acceptable values. This is probably the case at other places (rating, votes, etc.) too.
        if (favoritePoints == 0) {
            favoritePoints = other.favoritePoints;
        }
        if (rating == 0) {
            rating = other.rating;
        }
        if (votes == 0) {
            votes = other.votes;
        }
        if (myVote == 0) {
            myVote = other.myVote;
        }
        if (!detailed && attributes.isEmpty()) {
            if (other.attributes != null) {
                attributes.addAll(other.attributes);
            }
        }
        if (waypoints.isEmpty()) {
            this.setWaypoints(other.waypoints, false);
        }
        else {
            final ArrayList<Waypoint> newPoints = new ArrayList<>(waypoints);
            Waypoint.mergeWayPoints(newPoints, other.waypoints, false);
            this.setWaypoints(newPoints, false);
        }
        if (spoilers == null) {
            spoilers = other.spoilers;
        }
        if (inventory == null) {
            // If inventoryItems is 0, it can mean both
            // "don't know" or "0 items". Since we cannot distinguish
            // them here, only populate inventoryItems from
            // old data when we have to do it for inventory.
            inventory = other.inventory;
            inventoryItems = other.inventoryItems;
        }
        if (logCounts.isEmpty()) {
            logCounts = other.logCounts;
        }

        // if cache has ORIGINAL type waypoint ... it is considered that it has modified coordinates, otherwise not
        userModifiedCoords = false;
        for (final Waypoint wpt : waypoints) {
            if (wpt.getWaypointType() == WaypointType.ORIGINAL) {
                userModifiedCoords = true;
                break;
            }
        }

        if (!reliableLatLon) {
            reliableLatLon = other.reliableLatLon;
        }

        return isEqualTo(other);
    }

    /**
     * Compare two caches quickly. For map and list fields only the references are compared !
     *
     * @param other
     *            the other cache to compare this one to
     * @return true if both caches have the same content
     */
    @SuppressWarnings("deprecation")
    @SuppressFBWarnings("FE_FLOATING_POINT_EQUALITY")
    private boolean isEqualTo(final Geocache other) {
        return detailed == other.detailed &&
                StringUtils.equalsIgnoreCase(geocode, other.geocode) &&
                StringUtils.equalsIgnoreCase(name, other.name) &&
                cacheType == other.cacheType &&
                size == other.size &&
                ObjectUtils.equals(found, other.found) &&
                ObjectUtils.equals(premiumMembersOnly, other.premiumMembersOnly) &&
                difficulty == other.difficulty &&
                terrain == other.terrain &&
                (coords != null ? coords.equals(other.coords) : null == other.coords) &&
                reliableLatLon == other.reliableLatLon &&
                ObjectUtils.equals(disabled, other.disabled) &&
                ObjectUtils.equals(archived, other.archived) &&
                listId == other.listId &&
                StringUtils.equalsIgnoreCase(ownerDisplayName, other.ownerDisplayName) &&
                StringUtils.equalsIgnoreCase(ownerUserId, other.ownerUserId) &&
                StringUtils.equalsIgnoreCase(getDescription(), other.getDescription()) &&
                StringUtils.equalsIgnoreCase(personalNote, other.personalNote) &&
                StringUtils.equalsIgnoreCase(getShortDescription(), other.getShortDescription()) &&
                StringUtils.equalsIgnoreCase(getLocation(), other.getLocation()) &&
                ObjectUtils.equals(favorite, other.favorite) &&
                favoritePoints == other.favoritePoints &&
                ObjectUtils.equals(onWatchlist, other.onWatchlist) &&
                (hidden != null ? hidden.equals(other.hidden) : null == other.hidden) &&
                StringUtils.equalsIgnoreCase(guid, other.guid) &&
                StringUtils.equalsIgnoreCase(getHint(), other.getHint()) &&
                StringUtils.equalsIgnoreCase(cacheId, other.cacheId) &&
                (direction != null ? direction.equals(other.direction) : null == other.direction) &&
                (distance != null ? distance.equals(other.distance) : null == other.distance) &&
                rating == other.rating &&
                votes == other.votes &&
                myVote == other.myVote &&
                inventoryItems == other.inventoryItems &&
                attributes == other.attributes &&
                waypoints == other.waypoints &&
                spoilers == other.spoilers &&
                inventory == other.inventory &&
                logCounts == other.logCounts &&
                ObjectUtils.equals(logOffline, other.logOffline) &&
                finalDefined == other.finalDefined;
    }

    public boolean hasTrackables() {
        return inventoryItems > 0;
    }

    public boolean canBeAddedToCalendar() {
        // is event type?
        if (!isEventCache()) {
            return false;
        }
        // has event date set?
        if (hidden == null) {
            return false;
        }
        // is not in the past?
        final Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        return hidden.compareTo(cal.getTime()) >= 0;
    }

    public boolean isEventCache() {
        return cacheType.getValue().isEvent();
    }

    public void logVisit(final Activity fromActivity) {
        if (!getConnector().canLog(this)) {
            ActivityMixin.showToast(fromActivity, fromActivity.getResources().getString(R.string.err_cannot_log_visit));
            return;
        }
        fromActivity.startActivity(LogCacheActivity.getLogCacheIntent(fromActivity, cacheId, geocode));
    }

    public void logOffline(final Activity fromActivity, final LogType logType) {
        final boolean mustIncludeSignature = StringUtils.isNotBlank(Settings.getSignature()) && Settings.isAutoInsertSignature();
        final String initial = mustIncludeSignature ? LogTemplateProvider.applyTemplates(Settings.getSignature(), new LogContext(this, null, true)) : "";
        logOffline(fromActivity, initial, Calendar.getInstance(), logType);
    }

    void logOffline(final Activity fromActivity, final String log, final Calendar date, final LogType logType) {
        if (logType == LogType.UNKNOWN) {
            return;
        }
        final boolean status = DataStore.saveLogOffline(geocode, date.getTime(), logType, log);

        final Resources res = fromActivity.getResources();
        if (status) {
            ActivityMixin.showToast(fromActivity, res.getString(R.string.info_log_saved));
            DataStore.saveVisitDate(geocode);
            logOffline = Boolean.TRUE;

            notifyChange();
        } else {
            ActivityMixin.showToast(fromActivity, res.getString(R.string.err_log_post_failed));
        }
    }

    public void clearOfflineLog() {
        DataStore.clearLogOffline(geocode);
        notifyChange();
    }

    @NonNull
    public List<LogType> getPossibleLogTypes() {
        return getConnector().getPossibleLogTypes(this);
    }

    public void openInBrowser(final Activity fromActivity) {
        if (getUrl() == null) {
            return;
        }
        final Intent viewIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getLongUrl()));

        // Check if cgeo is the default, show the chooser to let the user choose a browser
        if (viewIntent.resolveActivity(fromActivity.getPackageManager()).getPackageName().equals(fromActivity.getPackageName())) {
            final Intent chooser = Intent.createChooser(viewIntent, fromActivity.getString(R.string.cache_menu_browser));

            final Intent internalBrowser = new Intent(fromActivity, SimpleWebviewActivity.class);
            internalBrowser.setData(Uri.parse(getUrl()));

            chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] {internalBrowser});


            fromActivity.startActivity(chooser);
        } else {
            fromActivity.startActivity(viewIntent);
        }
    }

    @NonNull
    private IConnector getConnector() {
        return ConnectorFactory.getConnector(this);
    }

    public boolean supportsRefresh() {
        return getConnector() instanceof ISearchByGeocode;
    }

    public boolean supportsWatchList() {
        return getConnector().supportsWatchList();
    }

    public boolean supportsFavoritePoints() {
        return getConnector().supportsFavoritePoints(this);
    }

    public boolean supportsLogging() {
        return getConnector().supportsLogging();
    }

    public boolean supportsLogImages() {
        return getConnector().supportsLogImages();
    }

    public boolean supportsOwnCoordinates() {
        return getConnector().supportsOwnCoordinates();
    }

    @NonNull
    public ILoggingManager getLoggingManager(final LogCacheActivity activity) {
        return getConnector().getLoggingManager(activity, this);
    }

    public float getDifficulty() {
        return difficulty;
    }

    @Override
    public String getGeocode() {
        return geocode;
    }

    /**
     * @return displayed owner, might differ from the real owner
     */
    public String getOwnerDisplayName() {
        return ownerDisplayName;
    }

    @NonNull
    public CacheSize getSize() {
        return size;
    }

    public float getTerrain() {
        return terrain;
    }

    public boolean isArchived() {
        return BooleanUtils.isTrue(archived);
    }

    public boolean isDisabled() {
        return BooleanUtils.isTrue(disabled);
    }

    public boolean isPremiumMembersOnly() {
        return BooleanUtils.isTrue(premiumMembersOnly);
    }

    public void setPremiumMembersOnly(final boolean members) {
        this.premiumMembersOnly = members;
    }

    /**
     *
     * @return {@code true} if the user is the owner of the cache, {@code false} otherwise
     */
    public boolean isOwner() {
        return getConnector().isOwner(this);
    }

    /**
     * @return GC username of the (actual) owner, might differ from the owner. Never empty.
     */
    @NonNull
    public String getOwnerUserId() {
        return ownerUserId;
    }

    /**
     * Attention, calling this method may trigger a database access for the cache!
     *
     * @return the decrypted hint
     */
    public String getHint() {
        initializeCacheTexts();
        assertTextNotNull(hint, "Hint");
        return hint;
    }

    /**
     * After lazy loading the lazily loaded field must be non {@code null}.
     *
     */
    private static void assertTextNotNull(final String field, final String name) throws InternalError {
        if (field == null) {
            throw new InternalError(name + " field is not allowed to be null here");
        }
    }

    /**
     * Attention, calling this method may trigger a database access for the cache!
     */
    public String getDescription() {
        initializeCacheTexts();
        assertTextNotNull(description, "Description");
        return description;
    }

    /**
     * loads long text parts of a cache on demand (but all fields together)
     */
    private void initializeCacheTexts() {
        if (description == null || shortdesc == null || hint == null || location == null) {
            if (inDatabase()) {
                final Geocache partial = DataStore.loadCacheTexts(this.getGeocode());
                if (description == null) {
                    setDescription(partial.getDescription());
                }
                if (shortdesc == null) {
                    setShortDescription(partial.getShortDescription());
                }
                if (hint == null) {
                    setHint(partial.getHint());
                }
                if (location == null) {
                    setLocation(partial.getLocation());
                }
            } else {
                description = StringUtils.defaultString(description);
                shortdesc = StringUtils.defaultString(shortdesc);
                hint = StringUtils.defaultString(hint);
                location = StringUtils.defaultString(location);
            }
        }
    }

    /**
     * Attention, calling this method may trigger a database access for the cache!
     */
    public String getShortDescription() {
        initializeCacheTexts();
        assertTextNotNull(shortdesc, "Short description");
        return shortdesc;
    }

    @Override
    public String getName() {
        return name;
    }

    public String getCacheId() {
        if (StringUtils.isBlank(cacheId) && getConnector().equals(GCConnector.getInstance())) {
            return String.valueOf(GCConstants.gccodeToGCId(geocode));
        }

        return cacheId;
    }

    public String getGuid() {
        return guid;
    }

    /**
     * Attention, calling this method may trigger a database access for the cache!
     */
    public String getLocation() {
        initializeCacheTexts();
        assertTextNotNull(location, "Location");
        return location;
    }

    public String getPersonalNote() {
        // non premium members have no personal notes, premium members have an empty string by default.
        // map both to null, so other code doesn't need to differentiate
        return StringUtils.defaultIfBlank(personalNote, null);
    }

    public boolean supportsCachesAround() {
        return getConnector() instanceof ISearchByCenter;
    }

    public void shareCache(@NonNull final Activity fromActivity, final Resources res) {
        final Intent intent = getShareIntent();

        fromActivity.startActivity(Intent.createChooser(intent, res.getText(R.string.cache_menu_share)));
    }

    @NonNull
    public Intent getShareIntent() {
        final StringBuilder subject = new StringBuilder("Geocache ");
        subject.append(geocode);
        if (StringUtils.isNotBlank(name)) {
            subject.append(" - ").append(name);
        }

        final Intent intent = new Intent(Intent.ACTION_SEND);
        intent.setType("text/plain");
        intent.putExtra(Intent.EXTRA_SUBJECT, subject.toString());
        intent.putExtra(Intent.EXTRA_TEXT, StringUtils.defaultString(getUrl()));

        return intent;
    }

    @Nullable
    public String getUrl() {
        return getConnector().getCacheUrl(this);
    }

    @Nullable
    public String getLongUrl() {
        return getConnector().getLongCacheUrl(this);
    }

    @Nullable
    public String getCgeoUrl() {
        return getConnector().getCacheUrl(this);
    }

    public boolean supportsGCVote() {
        return StringUtils.startsWithIgnoreCase(geocode, "GC");
    }

    public void setDescription(final String description) {
        this.description = description;
    }

    public boolean isFound() {
        return BooleanUtils.isTrue(found);
    }

    /**
     *
     * @return {@code true} if the user has put a favorite point onto this cache
     */
    public boolean isFavorite() {
        return BooleanUtils.isTrue(favorite);
    }

    public void setFavorite(final boolean favorite) {
        this.favorite = favorite;
    }

    @Nullable
    public Date getHiddenDate() {
        return hidden;
    }

    @NonNull
    public List<String> getAttributes() {
        return attributes.getUnderlyingList();
    }

    public List<Trackable> getInventory() {
        return inventory;
    }

    public void addSpoiler(final Image spoiler) {
        if (spoilers == null) {
            spoilers = new ArrayList<>();
        }
        spoilers.add(spoiler);
    }

    @NonNull
    public List<Image> getSpoilers() {
        return ListUtils.unmodifiableList(ListUtils.emptyIfNull(spoilers));
    }

    /**
     * @return a statistic how often the caches has been found, disabled, archived etc.
     */
    public Map<LogType, Integer> getLogCounts() {
        return logCounts;
    }

    public int getFavoritePoints() {
        return favoritePoints;
    }

    /**
     * @return the normalized cached name to be used for sorting, taking into account the numerical parts in the name
     */
    public String getNameForSorting() {
        if (null == nameForSorting) {
            nameForSorting = name;
            // pad each number part to a fixed size of 6 digits, so that numerical sorting becomes equivalent to string sorting
            MatcherWrapper matcher = new MatcherWrapper(NUMBER_PATTERN, nameForSorting);
            int start = 0;
            while (matcher.find(start)) {
                final String number = matcher.group();
                nameForSorting = StringUtils.substring(nameForSorting, 0, matcher.start()) + StringUtils.leftPad(number, 6, '0') + StringUtils.substring(nameForSorting, matcher.start() + number.length());
                start = matcher.start() + Math.max(6, number.length());
                matcher = new MatcherWrapper(NUMBER_PATTERN, nameForSorting);
            }
        }
        return nameForSorting;
    }

    public boolean isVirtual() {
        return cacheType.getValue().isVirtual();
    }

    public boolean showSize() {
        return !(size == CacheSize.NOT_CHOSEN || isEventCache() || isVirtual());
    }

    public long getUpdated() {
        return updated;
    }

    public void setUpdated(final long updated) {
        this.updated = updated;
    }

    public long getDetailedUpdate() {
        return detailedUpdate;
    }

    public void setDetailedUpdate(final long detailedUpdate) {
        this.detailedUpdate = detailedUpdate;
    }

    public long getVisitedDate() {
        return visitedDate;
    }

    public void setVisitedDate(final long visitedDate) {
        this.visitedDate = visitedDate;
    }

    public int getListId() {
        return listId;
    }

    public void setListId(final int listId) {
        this.listId = listId;
    }

    public boolean isDetailed() {
        return detailed;
    }

    public void setDetailed(final boolean detailed) {
        this.detailed = detailed;
    }

    public void setHidden(final Date hidden) {
        if (hidden == null) {
            this.hidden = null;
        }
        else {
            this.hidden = new Date(hidden.getTime()); // avoid storing the external reference in this object
        }
    }

    public Float getDirection() {
        return direction;
    }

    public void setDirection(final Float direction) {
        this.direction = direction;
    }

    public Float getDistance() {
        return distance;
    }

    public void setDistance(final Float distance) {
        this.distance = distance;
    }

    @Override
    public Geopoint getCoords() {
        return coords.getValue();
    }

    public int getCoordZoomLevel() {
        return coords.getCertaintyLevel();
    }

    /**
     * Set reliable coordinates
     */
    public void setCoords(final Geopoint coords) {
        this.coords = new UncertainProperty<>(coords);
    }

    /**
     * Set unreliable coordinates from a certain map zoom level
     */
    public void setCoords(final Geopoint coords, final int zoomlevel) {
        this.coords = new UncertainProperty<>(coords, zoomlevel);
    }

    /**
     * @return true if the coords are from the cache details page and the user has been logged in
     */
    public boolean isReliableLatLon() {
        return getConnector().isReliableLatLon(reliableLatLon);
    }

    public void setReliableLatLon(final boolean reliableLatLon) {
        this.reliableLatLon = reliableLatLon;
    }

    public void setShortDescription(final String shortdesc) {
        this.shortdesc = shortdesc;
    }

    public void setFavoritePoints(final int favoriteCnt) {
        this.favoritePoints = favoriteCnt;
    }

    public float getRating() {
        return rating;
    }

    public void setRating(final float rating) {
        this.rating = rating;
    }

    public int getVotes() {
        return votes;
    }

    public void setVotes(final int votes) {
        this.votes = votes;
    }

    public float getMyVote() {
        return myVote;
    }

    public void setMyVote(final float myVote) {
        this.myVote = myVote;
    }

    public int getInventoryItems() {
        return inventoryItems;
    }

    public void setInventoryItems(final int inventoryItems) {
        this.inventoryItems = inventoryItems;
    }

    /**
     * @return {@code true} if the cache is on the user's watchlist, {@code false} otherwise
     */
    public boolean isOnWatchlist() {
        return BooleanUtils.isTrue(onWatchlist);
    }

    public void setOnWatchlist(final boolean onWatchlist) {
        this.onWatchlist = onWatchlist;
    }

    /**
     * return an immutable list of waypoints.
     *
     * @return always non <code>null</code>
     */
    @NonNull
    public List<Waypoint> getWaypoints() {
        return waypoints.getUnderlyingList();
    }

    /**
     * @param waypoints
     *            List of waypoints to set for cache
     * @param saveToDatabase
     *            Indicates whether to add the waypoints to the database. Should be false if
     *            called while loading or building a cache
     * @return <code>true</code> if waypoints successfully added to waypoint database
     */
    public boolean setWaypoints(final List<Waypoint> waypoints, final boolean saveToDatabase) {
        this.waypoints.clear();
        if (waypoints != null) {
            this.waypoints.addAll(waypoints);
        }
        finalDefined = false;
        if (waypoints != null) {
            for (final Waypoint waypoint : waypoints) {
                waypoint.setGeocode(geocode);
                if (waypoint.isFinalWithCoords()) {
                    finalDefined = true;
                }
            }
        }
        return saveToDatabase && DataStore.saveWaypoints(this);
    }

    /**
     * The list of logs is immutable, because it is directly fetched from the database on demand, and not stored at this
     * object. If you want to modify logs, you have to load all logs of the cache, create a new list from the existing
     * list and store that new list in the database.
     *
     * @return immutable list of logs
     */
    @NonNull
    public List<LogEntry> getLogs() {
        return inDatabase() ? DataStore.loadLogs(geocode) : Collections.<LogEntry>emptyList();
    }

    /**
     * @return only the logs of friends
     */
    @NonNull
    public List<LogEntry> getFriendsLogs() {
        final ArrayList<LogEntry> friendLogs = new ArrayList<>();
        for (final LogEntry log : getLogs()) {
            if (log.friend) {
                friendLogs.add(log);
            }
        }
        return Collections.unmodifiableList(friendLogs);
    }

    public boolean isLogOffline() {
        return BooleanUtils.isTrue(logOffline);
    }

    public void setLogOffline(final boolean logOffline) {
        this.logOffline = logOffline;
    }

    public boolean isStatusChecked() {
        return statusChecked;
    }

    public void setStatusChecked(final boolean statusChecked) {
        this.statusChecked = statusChecked;
    }

    public String getDirectionImg() {
        return directionImg;
    }

    public void setDirectionImg(final String directionImg) {
        this.directionImg = directionImg;
    }

    public void setGeocode(@NonNull final String geocode) {
        this.geocode = StringUtils.upperCase(geocode);
    }

    public void setCacheId(final String cacheId) {
        this.cacheId = cacheId;
    }

    public void setGuid(final String guid) {
        this.guid = guid;
    }

    public void setName(final String name) {
        this.name = name;
    }

    public void setOwnerDisplayName(final String ownerDisplayName) {
        this.ownerDisplayName = ownerDisplayName;
    }

    public void setOwnerUserId(final String ownerUserId) {
        this.ownerUserId = ownerUserId;
    }

    public void setHint(final String hint) {
        this.hint = hint;
    }

    public void setSize(@NonNull final CacheSize size) {
        this.size = size;
    }

    public void setDifficulty(final float difficulty) {
        this.difficulty = difficulty;
    }

    public void setTerrain(final float terrain) {
        this.terrain = terrain;
    }

    public void setLocation(final String location) {
        this.location = location;
    }

    public void setPersonalNote(final String personalNote) {
        this.personalNote = StringUtils.trimToNull(personalNote);
    }

    public void setDisabled(final boolean disabled) {
        this.disabled = disabled;
    }

    public void setArchived(final boolean archived) {
        this.archived = archived;
    }

    public void setFound(final boolean found) {
        this.found = found;
    }

    public void setAttributes(final List<String> attributes) {
        this.attributes.clear();
        if (attributes != null) {
            this.attributes.addAll(attributes);
        }
    }

    public void setSpoilers(final List<Image> spoilers) {
        this.spoilers = spoilers;
    }

    public void setInventory(final List<Trackable> inventory) {
        this.inventory = inventory;
    }

    public void setLogCounts(final Map<LogType, Integer> logCounts) {
        this.logCounts = logCounts;
    }

    /*
     * (non-Javadoc)
     *
     * @see cgeo.geocaching.IBasicCache#getType()
     *
     * @returns Never null
     */
    public CacheType getType() {
        return cacheType.getValue();
    }

    public void setType(final CacheType cacheType) {
        if (cacheType == null || CacheType.ALL == cacheType) {
            throw new IllegalArgumentException("Illegal cache type");
        }
        this.cacheType = new UncertainProperty<>(cacheType);
    }

    public void setType(final CacheType cacheType, final int zoomlevel) {
        if (cacheType == null || CacheType.ALL == cacheType) {
            throw new IllegalArgumentException("Illegal cache type");
        }
        this.cacheType = new UncertainProperty<>(cacheType, zoomlevel);
    }

    public boolean hasDifficulty() {
        return difficulty > 0f;
    }

    public boolean hasTerrain() {
        return terrain > 0f;
    }

    /**
     * @return the storageLocation
     */
    public EnumSet<StorageLocation> getStorageLocation() {
        return storageLocation;
    }

    /**
     * @param storageLocation
     *            the storageLocation to set
     */
    public void addStorageLocation(final StorageLocation storageLocation) {
        this.storageLocation.add(storageLocation);
    }

    /**
     * Check if this cache instance comes from or has been stored into the database.
     */
    public boolean inDatabase() {
        return storageLocation.contains(StorageLocation.DATABASE);
    }

    /**
     * @param waypoint
     *            Waypoint to add to the cache
     * @param saveToDatabase
     *            Indicates whether to add the waypoint to the database. Should be false if
     *            called while loading or building a cache
     * @return <code>true</code> if waypoint successfully added to waypoint database
     */
    public boolean addOrChangeWaypoint(final Waypoint waypoint, final boolean saveToDatabase) {
        waypoint.setGeocode(geocode);

        if (waypoint.getId() < 0) { // this is a new waypoint
            assignUniquePrefix(waypoint);
            waypoints.add(waypoint);
            if (waypoint.isFinalWithCoords()) {
                finalDefined = true;
            }
        } else { // this is a waypoint being edited
            final int index = getWaypointIndex(waypoint);
            if (index >= 0) {
                final Waypoint oldWaypoint = waypoints.remove(index);
                waypoint.setPrefix(oldWaypoint.getPrefix());
                //migration
                if (StringUtils.isBlank(waypoint.getPrefix())
                        || StringUtils.equalsIgnoreCase(waypoint.getPrefix(), Waypoint.PREFIX_OWN)) {
                    assignUniquePrefix(waypoint);
                }
            }
            waypoints.add(waypoint);
            // when waypoint was edited, finalDefined may have changed
            resetFinalDefined();
        }
        return saveToDatabase && DataStore.saveWaypoint(waypoint.getId(), geocode, waypoint);
    }

    /*
     * Assigns a unique two-digit (compatibility with gc.com)
     * prefix within the scope of this cache.
     */
    private void assignUniquePrefix(final Waypoint waypoint) {
        // gather existing prefixes
        final Set<String> assignedPrefixes = new HashSet<>();
        for (final Waypoint wp : waypoints) {
            assignedPrefixes.add(wp.getPrefix());
        }

        for (int i = OWN_WP_PREFIX_OFFSET; i < 100; i++) {
            final String prefixCandidate = StringUtils.leftPad(String.valueOf(i), 2, '0');
            if (!assignedPrefixes.contains(prefixCandidate)) {
                waypoint.setPrefix(prefixCandidate);
                break;
            }
        }

    }

    public boolean hasWaypoints() {
        return !waypoints.isEmpty();
    }

    public boolean hasFinalDefined() {
        return finalDefined;
    }

    // Only for loading
    public void setFinalDefined(final boolean finalDefined) {
        this.finalDefined = finalDefined;
    }

    /**
     * Reset <code>finalDefined</code> based on current list of stored waypoints
     */
    private void resetFinalDefined() {
        finalDefined = false;
        for (final Waypoint wp : waypoints) {
            if (wp.isFinalWithCoords()) {
                finalDefined = true;
                break;
            }
        }
    }

    public boolean hasUserModifiedCoords() {
        return userModifiedCoords;
    }

    public void setUserModifiedCoords(final boolean coordsChanged) {
        userModifiedCoords = coordsChanged;
    }

    /**
     * Duplicate a waypoint.
     *
     * @param original
     *            the waypoint to duplicate
     * @return <code>true</code> if the waypoint was duplicated, <code>false</code> otherwise (invalid index)
     */
    public boolean duplicateWaypoint(final Waypoint original) {
        if (original == null) {
            return false;
        }
        final int index = getWaypointIndex(original);
        final Waypoint copy = new Waypoint(original);
        copy.setUserDefined();
        copy.setName(CgeoApplication.getInstance().getString(R.string.waypoint_copy_of) + " " + copy.getName());
        waypoints.add(index + 1, copy);
        return DataStore.saveWaypoint(-1, geocode, copy);
    }

    /**
     * delete a user defined waypoint
     *
     * @param waypoint
     *            to be removed from cache
     * @return <code>true</code>, if the waypoint was deleted
     */
    public boolean deleteWaypoint(final Waypoint waypoint) {
        if (waypoint == null) {
            return false;
        }
        if (waypoint.getId() < 0) {
            return false;
        }
        if (waypoint.isUserDefined()) {
            final int index = getWaypointIndex(waypoint);
            waypoints.remove(index);
            DataStore.deleteWaypoint(waypoint.getId());
            DataStore.removeCache(geocode, EnumSet.of(RemoveFlag.CACHE));
            // Check status if Final is defined
            if (waypoint.isFinalWithCoords()) {
                resetFinalDefined();
            }
            return true;
        }
        return false;
    }

    /**
     * deletes any waypoint
     */

    public void deleteWaypointForce(final Waypoint waypoint) {
        final int index = getWaypointIndex(waypoint);
        waypoints.remove(index);
        DataStore.deleteWaypoint(waypoint.getId());
        DataStore.removeCache(geocode, EnumSet.of(RemoveFlag.CACHE));
        resetFinalDefined();
    }

    /**
     * Find index of given <code>waypoint</code> in cache's <code>waypoints</code> list
     *
     * @param waypoint
     *            to find index for
     * @return index in <code>waypoints</code> if found, -1 otherwise
     */
    private int getWaypointIndex(final Waypoint waypoint) {
        final int id = waypoint.getId();
        for (int index = 0; index < waypoints.size(); index++) {
            if (waypoints.get(index).getId() == id) {
                return index;
            }
        }
        return -1;
    }

    /**
     * Lookup a waypoint by its id.
     *
     * @param id
     *            the id of the waypoint to look for
     * @return waypoint or <code>null</code>
     */
    public Waypoint getWaypointById(final int id) {
        for (final Waypoint waypoint : waypoints) {
            if (waypoint.getId() == id) {
                return waypoint;
            }
        }
        return null;
    }

    /**
     * Detect coordinates in the personal note and convert them to user defined waypoints. Works by rule of thumb.
     */
    public boolean parseWaypointsFromNote() {
        boolean changed = false;
        for (final Waypoint waypoint : Waypoint.parseWaypointsFromNote(StringUtils.defaultString(getPersonalNote()))) {
            if (!hasIdenticalWaypoint(waypoint.getCoords())) {
                addOrChangeWaypoint(waypoint, false);
                changed = true;
            }
        }
        return changed;
    }

    private boolean hasIdenticalWaypoint(final Geopoint point) {
        for (final Waypoint waypoint: waypoints) {
            // waypoint can have no coords such as a Final set by cache owner
            final Geopoint coords = waypoint.getCoords();
            if (coords != null && coords.equals(point)) {
                return true;
            }
        }
        return false;
    }

    /*
     * For working in the debugger
     * (non-Javadoc)
     *
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return this.geocode + " " + this.name;
    }

    @Override
    public int hashCode() {
        return StringUtils.defaultString(geocode).hashCode();
    }

    @Override
    public boolean equals(final Object obj) {
        // TODO: explain the following line or remove this non-standard equality method
        // just compare the geocode even if that is not what "equals" normally does
        return this == obj || (obj instanceof Geocache && StringUtils.isNotEmpty(geocode) && geocode.equals(((Geocache) obj).geocode));
    }

    public void store(final CancellableHandler handler) {
        store(StoredList.TEMPORARY_LIST.id, handler);
    }

    public void store(final int listId, final CancellableHandler handler) {
        final int newListId = listId < StoredList.STANDARD_LIST_ID
                ? Math.max(getListId(), StoredList.STANDARD_LIST_ID)
                : listId;
        storeCache(this, null, newListId, false, handler);
    }

    @Override
    public int getId() {
        return 0;
    }

    @Override
    public WaypointType getWaypointType() {
        return null;
    }

    @Override
    public String getCoordType() {
        return "cache";
    }

    public Subscription drop(final Handler handler) {
        return Schedulers.io().createWorker().schedule(new Action0() {
            @Override
            public void call() {
                try {
                    dropSynchronous();
                    handler.sendMessage(Message.obtain());
                } catch (final Exception e) {
                    Log.e("cache.drop: ", e);
                }
            }
        });
    }

    public void dropSynchronous() {
        DataStore.markDropped(Collections.singletonList(this));
        DataStore.removeCache(getGeocode(), EnumSet.of(RemoveFlag.CACHE));
    }

    private void warnIncorrectParsingIf(final boolean incorrect, final String field) {
        if (incorrect) {
            Log.w(field + " not parsed correctly for " + geocode);
        }
    }

    private void warnIncorrectParsingIfBlank(final String str, final String field) {
        warnIncorrectParsingIf(StringUtils.isBlank(str), field);
    }

    public void checkFields() {
        warnIncorrectParsingIfBlank(getGeocode(), "geo");
        warnIncorrectParsingIfBlank(getName(), "name");
        warnIncorrectParsingIfBlank(getGuid(), "guid");
        warnIncorrectParsingIf(getTerrain() == 0.0, "terrain");
        warnIncorrectParsingIf(getDifficulty() == 0.0, "difficulty");
        warnIncorrectParsingIfBlank(getOwnerDisplayName(), "owner");
        warnIncorrectParsingIfBlank(getOwnerUserId(), "owner");
        warnIncorrectParsingIf(getHiddenDate() == null, "hidden");
        warnIncorrectParsingIf(getFavoritePoints() < 0, "favoriteCount");
        warnIncorrectParsingIf(getSize() == CacheSize.UNKNOWN, "size");
        warnIncorrectParsingIf(getType() == null || getType() == CacheType.UNKNOWN, "type");
        warnIncorrectParsingIf(getCoords() == null, "coordinates");
        warnIncorrectParsingIfBlank(getLocation(), "location");
    }

    public Subscription refresh(final CancellableHandler handler, final Scheduler scheduler) {
        return scheduler.createWorker().schedule(new Action0() {
            @Override
            public void call() {
                refreshSynchronous(handler);
            }
        });
    }

    public void refreshSynchronous(final CancellableHandler handler) {
        DataStore.removeCache(geocode, EnumSet.of(RemoveFlag.CACHE));
        storeCache(null, geocode, listId, true, handler);
    }

    public static void storeCache(final Geocache origCache, final String geocode, final int listId, final boolean forceRedownload, final CancellableHandler handler) {
        try {
            Geocache cache = null;
            // get cache details, they may not yet be complete
            if (origCache != null) {
                SearchResult search = null;
                // only reload the cache if it was already stored or doesn't have full details (by checking the description)
                if (origCache.isOffline() || StringUtils.isBlank(origCache.getDescription())) {
                    search = searchByGeocode(origCache.getGeocode(), null, listId, false, handler);
                }
                if (search != null) {
                    cache = search.getFirstCacheFromResult(LoadFlags.LOAD_CACHE_OR_DB);
                } else {
                    cache = origCache;
                }
            } else if (StringUtils.isNotBlank(geocode)) {
                final SearchResult search = searchByGeocode(geocode, null, listId, forceRedownload, handler);
                if (search != null) {
                    cache = search.getFirstCacheFromResult(LoadFlags.LOAD_CACHE_OR_DB);
                }
            }

            if (cache == null) {
                if (handler != null) {
                    handler.sendMessage(Message.obtain());
                }

                return;
            }

            if (CancellableHandler.isCancelled(handler)) {
                return;
            }

            final HtmlImage imgGetter = new HtmlImage(cache.getGeocode(), false, listId, true);

            // store images from description
            if (StringUtils.isNotBlank(cache.getDescription())) {
                Html.fromHtml(cache.getDescription(), imgGetter, null);
            }

            if (CancellableHandler.isCancelled(handler)) {
                return;
            }

            // store spoilers
            if (CollectionUtils.isNotEmpty(cache.getSpoilers())) {
                for (final Image oneSpoiler : cache.getSpoilers()) {
                    imgGetter.getDrawable(oneSpoiler.getUrl());
                }
            }

            if (CancellableHandler.isCancelled(handler)) {
                return;
            }

            // store images from logs
            if (Settings.isStoreLogImages()) {
                for (final LogEntry log : cache.getLogs()) {
                    if (log.hasLogImages()) {
                        for (final Image oneLogImg : log.getLogImages()) {
                            imgGetter.getDrawable(oneLogImg.getUrl());
                        }
                    }
                }
            }

            if (CancellableHandler.isCancelled(handler)) {
                return;
            }

            cache.setListId(listId);
            DataStore.saveCache(cache, EnumSet.of(SaveFlag.DB));

            if (CancellableHandler.isCancelled(handler)) {
                return;
            }

            RxUtils.waitForCompletion(StaticMapsProvider.downloadMaps(cache), imgGetter.waitForEndObservable(handler));

            if (handler != null) {
                handler.sendEmptyMessage(CancellableHandler.DONE);
            }
        } catch (final Exception e) {
            Log.e("Geocache.storeCache", e);
        }
    }

    public static SearchResult searchByGeocode(final String geocode, final String guid, final int listId, final boolean forceReload, final CancellableHandler handler) {
        if (StringUtils.isBlank(geocode) && StringUtils.isBlank(guid)) {
            Log.e("Geocache.searchByGeocode: No geocode nor guid given");
            return null;
        }

        if (!forceReload && listId == StoredList.TEMPORARY_LIST.id && (DataStore.isOffline(geocode, guid) || DataStore.isThere(geocode, guid, true, true))) {
            final SearchResult search = new SearchResult();
            final String realGeocode = StringUtils.isNotBlank(geocode) ? geocode : DataStore.getGeocodeForGuid(guid);
            search.addGeocode(realGeocode);
            return search;
        }

        // if we have no geocode, we can't dynamically select the handler, but must explicitly use GC
        if (geocode == null) {
            return GCConnector.getInstance().searchByGeocode(null, guid, handler);
        }

        final IConnector connector = ConnectorFactory.getConnector(geocode);
        if (connector instanceof ISearchByGeocode) {
            return ((ISearchByGeocode) connector).searchByGeocode(geocode, guid, handler);
        }
        return null;
    }

    public boolean isOffline() {
        return listId >= StoredList.STANDARD_LIST_ID;
    }

    /**
     * guess an event start time from the description
     *
     * @return start time in minutes after midnight
     */
    public int guessEventTimeMinutes() {
        if (!isEventCache()) {
            return -1;
        }

        final String hourLocalized = CgeoApplication.getInstance().getString(R.string.cache_time_full_hours);
        final ArrayList<Pattern> patterns = new ArrayList<>();

        // 12:34
        patterns.add(Pattern.compile("\\b(\\d{1,2})\\:(\\d\\d)\\b"));
        if (StringUtils.isNotBlank(hourLocalized)) {
            // 17 - 20 o'clock
            patterns.add(Pattern.compile("\\b(\\d{1,2})(?:\\.00)?" + "\\s*(?:-|[a-z]+)\\s*" + "(?:\\d{1,2})(?:\\.00)?" + "\\s+" + Pattern.quote(hourLocalized), Pattern.CASE_INSENSITIVE));
            // 12 o'clock, 12.00 o'clock
            patterns.add(Pattern.compile("\\b(\\d{1,2})(?:\\.(00|15|30|45))?\\s+" + Pattern.quote(hourLocalized), Pattern.CASE_INSENSITIVE));
        }

        final String searchText = getShortDescription() + ' ' + getDescription();
        for (final Pattern pattern : patterns) {
            final MatcherWrapper matcher = new MatcherWrapper(pattern, searchText);
            while (matcher.find()) {
                try {
                    final int hours = Integer.parseInt(matcher.group(1));
                    int minutes = 0;
                    if (matcher.groupCount() >= 2 && !StringUtils.isEmpty(matcher.group(2))) {
                        minutes = Integer.parseInt(matcher.group(2));
                    }
                    if (hours >= 0 && hours < 24 && minutes >= 0 && minutes < 60) {
                        return hours * 60 + minutes;
                    }
                } catch (final NumberFormatException ignored) {
                    // cannot happen, but static code analysis doesn't know
                }
            }
        }
        return -1;
    }

    public boolean hasStaticMap() {
        return StaticMapsProvider.hasStaticMap(this);
    }

    @NonNull
    public Collection<Image> getImages() {
        final LinkedList<Image> result = new LinkedList<>();
        result.addAll(getSpoilers());
        addLocalSpoilersTo(result);
        for (final LogEntry log : getLogs()) {
            result.addAll(log.getLogImages());
        }
        ImageUtils.addImagesFromHtml(result, geocode, getShortDescription(), getDescription());
        return result;
    }

    /**
     * Add spoilers stored locally in <tt>/sdcard/GeocachePhotos</tt>. If a cache is named GC123ABC, the
     * directory will be <tt>/sdcard/GeocachePhotos/C/B/GC123ABC/</tt>.
     *
     * @param spoilers the list to add to
     */
    private void addLocalSpoilersTo(final List<Image> spoilers) {
        if (StringUtils.length(geocode) >= 2) {
            final String suffix = StringUtils.right(geocode, 2);
            final File baseDir = new File(Environment.getExternalStorageDirectory(), "GeocachePhotos");
            final File lastCharDir = new File(baseDir, suffix.substring(1));
            final File secondToLastCharDir = new File(lastCharDir, suffix.substring(0, 1));
            final File finalDir = new File(secondToLastCharDir, geocode);
            final File[] files = finalDir.listFiles();
            if (files != null) {
                for (final File image : files) {
                    spoilers.add(new Image("file://" + image.getAbsolutePath(), image.getName()));
                }
            }
        }
    }

    public void setDetailedUpdatedNow() {
        final long now = System.currentTimeMillis();
        setUpdated(now);
        setDetailedUpdate(now);
        setDetailed(true);
    }

    /**
     * Gets whether the user has logged the specific log type for this cache. Only checks the currently stored logs of
     * the cache, so the result might be wrong.
     */
    public boolean hasOwnLog(final LogType logType) {
        for (final LogEntry logEntry : getLogs()) {
            if (logEntry.type == logType && logEntry.isOwn()) {
                return true;
            }
        }
        return false;
    }

    public int getMapMarkerId() {
        return getConnector().getCacheMapMarkerId(isDisabled() || isArchived());
    }

    public boolean isLogPasswordRequired() {
        return logPasswordRequired;
    }

    public void setLogPasswordRequired(final boolean required) {
        logPasswordRequired = required;
    }

    public String getWaypointGpxId(final String prefix) {
        return getConnector().getWaypointGpxId(prefix, geocode);
    }

    @NonNull
    public String getWaypointPrefix(final String name) {
        return getConnector().getWaypointPrefix(name);
    }

    /**
     * Get number of overall finds for a cache, or 0 if the number of finds is not known.
     */
    public int getFindsCount() {
        if (getLogCounts().isEmpty()) {
            setLogCounts(inDatabase() ? DataStore.loadLogCounts(getGeocode()) : Collections.<LogType, Integer>emptyMap());
        }
        final Integer logged = getLogCounts().get(LogType.FOUND_IT);
        if (logged != null) {
            return logged;
        }
        return 0;
    }

    public boolean applyDistanceRule() {
        return (getType().applyDistanceRule() || hasUserModifiedCoords()) && getConnector() == GCConnector.getInstance();
    }

    @NonNull
    public LogType getDefaultLogType() {
        if (isEventCache()) {
            final Date eventDate = getHiddenDate();
            final boolean expired = CalendarUtils.isPastEvent(this);

            if (hasOwnLog(LogType.WILL_ATTEND) || expired || (eventDate != null && CalendarUtils.daysSince(eventDate.getTime()) == 0)) {
                return hasOwnLog(LogType.ATTENDED) ? LogType.NOTE : LogType.ATTENDED;
            }
            return LogType.WILL_ATTEND;
        }
        if (isFound()) {
            return LogType.NOTE;
        }
        if (getType() == CacheType.WEBCAM) {
            return LogType.WEBCAM_PHOTO_TAKEN;
        }
        return LogType.FOUND_IT;
    }

    /**
     * Get the geocodes of a collection of caches.
     *
     * @param caches a collection of caches
     * @return the non-blank geocodes of the caches
     */
    @NonNull
    public static Set<String> getGeocodes(@NonNull final Collection<Geocache> caches) {
        final Set<String> geocodes = new HashSet<>(caches.size());
        for (final Geocache cache : caches) {
            final String geocode = cache.getGeocode();
            if (StringUtils.isNotBlank(geocode)) {
                geocodes.add(geocode);
            }
        }
        return geocodes;
    }

    /**
     * Show the hint as toast message. If no hint is available, a default "no hint available" will be shown instead.
     */
    public void showHintToast(final Activity activity) {
        final String hint = getHint();
        ActivityMixin.showToast(activity, StringUtils.defaultIfBlank(hint, activity.getString(R.string.cache_hint_not_available)));
    }

}