Welcome to mirror list, hosted at ThFree Co, Russian Federation.

JtxICalObject.kt « ical4android « bitfire « at « java « main « src - github.com/bitfireAT/ical4android.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
blob: e898ad18d5612c1558e4aee3a0b2575d5928f885 (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
/***************************************************************************************************
 * Copyright © All Contributors. See LICENSE and AUTHORS in the root directory for details.
 **************************************************************************************************/

package at.bitfire.ical4android

import android.content.ContentUris
import android.content.ContentValues
import android.net.ParseException
import android.net.Uri
import android.os.ParcelFileDescriptor
import android.util.Base64
import at.bitfire.ical4android.MiscUtils.CursorHelper.toValues
import at.techbee.jtx.JtxContract
import at.techbee.jtx.JtxContract.JtxICalObject.TZ_ALLDAY
import at.techbee.jtx.JtxContract.asSyncAdapter
import net.fortuna.ical4j.data.CalendarOutputter
import net.fortuna.ical4j.data.ParserException
import net.fortuna.ical4j.model.*
import net.fortuna.ical4j.model.Calendar
import net.fortuna.ical4j.model.Date
import net.fortuna.ical4j.model.component.VAlarm
import net.fortuna.ical4j.model.component.VJournal
import net.fortuna.ical4j.model.component.VToDo
import net.fortuna.ical4j.model.parameter.*
import net.fortuna.ical4j.model.property.*
import java.io.*
import java.net.URI
import java.net.URISyntaxException
import java.time.format.DateTimeParseException
import java.util.*
import java.util.TimeZone
import java.util.logging.Level

open class JtxICalObject(
    val collection: JtxCollection<JtxICalObject>
) {

    var id: Long = 0L
    lateinit var component: String
    var summary: String? = null
    var description: String? = null
    var dtstart: Long? = null
    var dtstartTimezone: String? = null
    var dtend: Long? = null
    var dtendTimezone: String? = null

    var classification: String? = null
    var status: String? = null

    var priority: Int? = null

    var due: Long? = null      // VTODO only!
    var dueTimezone: String? = null //VTODO only!
    var completed: Long? = null // VTODO only!
    var completedTimezone: String? = null //VTODO only!
    var duration: String? = null //VTODO only!

    var percent: Int? = null
    var url: String? = null
    var contact: String? = null
    var geoLat: Double? = null
    var geoLong: Double? = null
    var location: String? = null
    var locationAltrep: String? = null

    var uid: String = "${System.currentTimeMillis()}-${UUID.randomUUID()}@at.techbee.jtx"

    var created: Long = System.currentTimeMillis()
    var dtstamp: Long = System.currentTimeMillis()
    var lastModified: Long = System.currentTimeMillis()
    var sequence: Long = 0

    var color: Int? = null

    var rrule: String? = null    //only for recurring events, see https://tools.ietf.org/html/rfc5545#section-3.8.5.3
    var exdate: String? = null   //only for recurring events, see https://tools.ietf.org/html/rfc5545#section-3.8.5.1
    var rdate: String? = null    //only for recurring events, see https://tools.ietf.org/html/rfc5545#section-3.8.5.2
    var recurid: String? = null  //only for recurring events, see https://tools.ietf.org/html/rfc5545#section-3.8.5

    var rstatus: String? = null

    var collectionId: Long = collection.id

    var dirty: Boolean = true
    var deleted: Boolean = false

    var fileName: String? = null
    var eTag: String? = null
    var scheduleTag: String? = null
    var flags: Int = 0

    var categories: MutableList<Category> = mutableListOf()
    var attachments: MutableList<Attachment> = mutableListOf()
    var attendees: MutableList<Attendee> = mutableListOf()
    var comments: MutableList<Comment> = mutableListOf()
    var organizer: Organizer? = null
    var resources: MutableList<Resource> = mutableListOf()
    var relatedTo: MutableList<RelatedTo> = mutableListOf()
    var alarms: MutableList<Alarm> = mutableListOf()
    var unknown: MutableList<Unknown> = mutableListOf()




    data class Category(
        var categoryId: Long = 0L,
        var text: String? = null,
        var language: String? = null,
        var other: String? = null
    )

    data class Attachment(
        var attachmentId: Long = 0L,
        var uri: String? = null,
        var binary: String? = null,
        var fmttype: String? = null,
        var other: String? = null,
        var filename: String? = null,
        var extension: String? = null,
        var filesize: Long? = null
    )

    data class Comment(
        var commentId: Long = 0L,
        var text: String? = null,
        var altrep: String? = null,
        var language: String? = null,
        var other: String? = null
    )

    data class RelatedTo(
        var relatedtoId: Long = 0L,
        var text: String? = null,
        var reltype: String? = null,
        var other: String? = null
    )

    data class Attendee(
        var attendeeId: Long = 0L,
        var caladdress: String? = null,
        var cutype: String? = JtxContract.JtxAttendee.Cutype.INDIVIDUAL.name,
        var member: String? = null,
        var role: String? = JtxContract.JtxAttendee.Role.`REQ-PARTICIPANT`.name,
        var partstat: String? = null,
        var rsvp: Boolean? = null,
        var delegatedto: String? = null,
        var delegatedfrom: String? = null,
        var sentby: String? = null,
        var cn: String? = null,
        var dir: String? = null,
        var language: String? = null,
        var other: String? = null
    )

    data class Resource(
        var resourceId: Long = 0L,
        var text: String? = null,
        var altrep: String? = null,
        var language: String? = null,
        var other: String? = null
    )

    data class Organizer(
        var organizerId: Long = 0L,
        var caladdress: String? = null,
        var cn: String? = null,
        var dir: String? = null,
        var sentby: String? = null,
        var language: String? = null,
        var other: String? = null
    )

    data class Alarm(
        var alarmId: Long = 0L,
        var action: String? = null,
        var description: String? = null,
        var summary: String? = null,
        var attendee: String? = null,
        var duration: String? = null,
        var repeat: String? = null,
        var attach: String? = null,
        var other: String? = null,
        var triggerTime: Long? = null,
        var triggerTimezone: String? = null,
        var triggerRelativeTo: String? = null,
        var triggerRelativeDuration: String? = null
    )

    data class Unknown(
        var unknownId: Long = 0L,
        var value: String? = null
    )


    companion object {

        const val X_PROP_COMPLETEDTIMEZONE = "X-COMPLETEDTIMEZONE"

        const val MAX_ATTACHMENT_SYNC_SIZE = 102400 // = 100KB

        /**
         * Parses an iCalendar resource, applies [ICalPreprocessor] to increase compatibility
         * and extracts the VTODOs and/or VJOURNALS.
         *
         * @param reader where the iCalendar is taken from
         *
         * @return array of filled [JtxICalObject] data objects (may have size 0)
         *
         * @throws ParserException when the iCalendar can't be parsed
         * @throws IllegalArgumentException when the iCalendar resource contains an invalid value
         * @throws IOException on I/O errors
         */
        @UsesThreadContextClassLoader
        fun fromReader(
            reader: Reader,
            collection: JtxCollection<JtxICalObject>
        ): List<JtxICalObject> {
            val ical = ICalendar.fromReader(reader)

            val iCalObjectList = mutableListOf<JtxICalObject>()

            ical.components.forEach { component ->

                val iCalObject = JtxICalObject(collection)
                when(component) {
                    is VToDo -> {
                        iCalObject.component = JtxContract.JtxICalObject.Component.VTODO.name
                        if (component.uid != null)
                            iCalObject.uid = component.uid.value                         // generated UID is overwritten here (if present)
                        extractProperties(iCalObject, component.properties)
                        extractVAlarms(iCalObject, component.components)                 // accessing the components needs an explicit type
                        iCalObjectList.add(iCalObject)
                    }
                    is VJournal -> {
                        iCalObject.component = JtxContract.JtxICalObject.Component.VJOURNAL.name
                        if (component.uid != null)
                            iCalObject.uid = component.uid.value
                        extractProperties(iCalObject, component.properties)
                        extractVAlarms(iCalObject, component.components)                  // accessing the components needs an explicit type
                        iCalObjectList.add(iCalObject)
                    }
                }
            }
            return iCalObjectList
        }

        /**
         * Extracts VAlarms from the given Component (VJOURNAL or VTODO). The VAlarm is supposed to be a component within the VJOURNAL or VTODO component.
         * Other components than VAlarms should not occur.
         * @param [iCalObject] where the VAlarms should be inserted
         * @param [calComponents] from which the VAlarms should be extracted
         */
        private fun extractVAlarms(iCalObject: JtxICalObject, calComponents: ComponentList<*>) {

            calComponents.forEach { component ->
                if(component is VAlarm) {
                    val jtxAlarm = Alarm().apply {
                        component.action?.value?.let { vAlarmAction -> this.action = vAlarmAction }
                        component.summary?.value?.let { vAlarmSummary -> this.summary = vAlarmSummary }
                        component.description?.value?.let { vAlarmDesc -> this.description = vAlarmDesc }
                        component.duration?.value?.let { vAlarmDur -> this.duration = vAlarmDur }
                        component.attachment?.uri?.let { uri -> this.attach = uri.toString() }
                        component.repeat?.value?.let { vAlarmRep -> this.repeat = vAlarmRep }

                        // alarms can have a duration or an absolute dateTime, but not both!
                        if(component.trigger.duration != null) {
                            component.trigger?.duration?.let { duration -> this.triggerRelativeDuration = duration.toString() }
                            component.trigger?.getParameter<Related>(Parameter.RELATED)?.let { related -> this.triggerRelativeTo = related.value }
                        } else if(component.trigger.dateTime != null) {
                            component.trigger?.dateTime?.let { dateTime -> this.triggerTime = dateTime.time  }
                            component.trigger?.dateTime?.timeZone?.let { timezone -> this.triggerTimezone = timezone.id }
                        }

                        // remove properties to add the rest to other
                        component.properties.remove(component.action)
                        component.properties.remove(component.summary)
                        component.properties.remove(component.description)
                        component.properties.remove(component.duration)
                        component.properties.remove(component.attachment)
                        component.properties.remove(component.repeat)
                        component.properties.remove(component.trigger)
                        component.properties?.let { vAlarmProps -> this.other = JtxContract.getJsonStringFromXProperties(vAlarmProps) }
                    }
                    iCalObject.alarms.add(jtxAlarm)
                }
            }
        }

        /**
         * Extracts properties from a given Property list and maps it to a JtxICalObject
         * @param [iCalObject] where the properties should be mapped to
         * @param [properties] from which the properties can be extracted
         */
        private fun extractProperties(iCalObject: JtxICalObject, properties: PropertyList<*>) {

            // sequence must only be null for locally created, not-yet-synchronized events
            iCalObject.sequence = 0

            for (prop in properties) {
                when (prop) {
                    is Sequence -> iCalObject.sequence = prop.sequenceNo.toLong()
                    is Created -> iCalObject.created = prop.dateTime.time
                    is LastModified -> iCalObject.lastModified = prop.dateTime.time
                    is Summary -> iCalObject.summary = prop.value
                    is Location -> {
                        iCalObject.location = prop.value
                        if(!prop.parameters.isEmpty && prop.parameters.getParameter<AltRep>(Parameter.ALTREP) != null)
                            iCalObject.locationAltrep = prop.parameters.getParameter<AltRep>(Parameter.ALTREP).value
                    }
                    is Geo -> {
                        iCalObject.geoLat = prop.latitude.toDouble()
                        iCalObject.geoLong = prop.longitude.toDouble()
                    }
                    is Description -> iCalObject.description = prop.value
                    is Color -> iCalObject.color = Css3Color.fromString(prop.value)?.argb
                    is Url -> iCalObject.url = prop.value
                    is Priority -> iCalObject.priority = prop.level
                    is Clazz -> iCalObject.classification = prop.value
                    is Status -> iCalObject.status = prop.value
                    is DtEnd -> Ical4Android.log.warning("The property DtEnd must not be used for VTODO and VJOURNAL, this value is rejected.")
                    is Completed -> {
                        if (iCalObject.component == JtxContract.JtxICalObject.Component.VTODO.name) {
                            iCalObject.completed = prop.date.time
                        } else
                            Ical4Android.log.warning("The property Completed is only supported for VTODO, this value is rejected.")
                    }

                    is Due -> {
                        if (iCalObject.component == JtxContract.JtxICalObject.Component.VTODO.name) {
                            iCalObject.due = prop.date.time
                            when {
                                prop.date is DateTime && prop.timeZone != null -> iCalObject.dueTimezone = prop.timeZone.id
                                prop.date is DateTime && prop.isUtc -> iCalObject.dueTimezone = TimeZone.getTimeZone("UTC").id
                                prop.date is DateTime && !prop.isUtc && prop.timeZone == null -> iCalObject.dueTimezone = null                   // this comparison is kept on purpose as "prop.date is Date" did not work as expected.
                                else -> iCalObject.dueTimezone = TZ_ALLDAY     // prop.date is Date (and not DateTime), therefore it must be Allday
                            }
                        } else
                            Ical4Android.log.warning("The property Due is only supported for VTODO, this value is rejected.")
                    }

                    is Duration -> iCalObject.duration = prop.value

                    is DtStart -> {
                        iCalObject.dtstart = prop.date.time
                        when {
                            prop.date is DateTime && prop.timeZone != null -> iCalObject.dtstartTimezone = prop.timeZone.id
                            prop.date is DateTime && prop.isUtc -> iCalObject.dtstartTimezone = TimeZone.getTimeZone("UTC").id
                            prop.date is DateTime && !prop.isUtc && prop.timeZone == null -> iCalObject.dtstartTimezone = null                   // this comparison is kept on purpose as "prop.date is Date" did not work as expected.
                            else -> iCalObject.dtstartTimezone = TZ_ALLDAY     // prop.date is Date (and not DateTime), therefore it must be Allday
                        }
                    }

                    is PercentComplete -> {
                        if (iCalObject.component == JtxContract.JtxICalObject.Component.VTODO.name)
                            iCalObject.percent = prop.percentage
                        else
                            Ical4Android.log.warning("The property PercentComplete is only supported for VTODO, this value is rejected.")
                    }

                    is RRule -> iCalObject.rrule = prop.value
                    is RDate -> {
                        val rdateList = if(iCalObject.rdate.isNullOrEmpty())
                            mutableListOf()
                        else
                            JtxContract.getLongListFromString(iCalObject.rdate!!)
                        prop.dates.forEach {
                            rdateList.add(it.time)
                        }
                        iCalObject.rdate = rdateList.toTypedArray().joinToString(separator = ",")
                    }
                    is ExDate -> {
                        val exdateList = if(iCalObject.exdate.isNullOrEmpty())
                            mutableListOf()
                        else
                            JtxContract.getLongListFromString(iCalObject.exdate!!)
                        prop.dates.forEach {
                            exdateList.add(it.time)
                        }
                        iCalObject.exdate = exdateList.toTypedArray().joinToString(separator = ",")
                    }
                    is RecurrenceId -> iCalObject.recurid = prop.value

                    //is RequestStatus -> iCalObject.rstatus = prop.value

                    is Categories ->
                        for (category in prop.categories)
                            iCalObject.categories.add(Category(text = category))

                    is net.fortuna.ical4j.model.property.Comment -> {
                        iCalObject.comments.add(
                            Comment().apply {
                                this.text = prop.value
                                this.language = prop.parameters?.getParameter<Language>(Parameter.LANGUAGE)?.value
                                this.altrep = prop.parameters?.getParameter<AltRep>(Parameter.ALTREP)?.value

                                // remove the known parameter
                                prop.parameters?.removeAll(Parameter.LANGUAGE)
                                prop.parameters?.removeAll(Parameter.ALTREP)

                                // save unknown parameters in the other field
                                this.other = JtxContract.getJsonStringFromXParameters(prop.parameters)
                            })

                    }

                    is Resources ->
                        for (resource in prop.resources)
                            iCalObject.resources.add(Resource(text = resource))

                    is Attach -> {
                        val attachment = Attachment()
                        prop.uri?.let { attachment.uri = it.toString() }
                        prop.binary?.let {
                            attachment.binary = Base64.encodeToString(it, Base64.DEFAULT)
                        }
                        prop.parameters?.getParameter<FmtType>(Parameter.FMTTYPE)?.let {
                            attachment.fmttype = it.value
                            prop.parameters?.remove(it)
                        }

                        attachment.other = JtxContract.getJsonStringFromXParameters(prop.parameters)

                        if (attachment.uri?.isNotEmpty() == true || attachment.binary?.isNotEmpty() == true)   // either uri or value must be present!
                            iCalObject.attachments.add(attachment)
                    }

                    is net.fortuna.ical4j.model.property.RelatedTo -> {

                        iCalObject.relatedTo.add(
                            RelatedTo().apply {
                                this.text = prop.value
                                this.reltype = prop.getParameter<RelType>(RelType.RELTYPE)?.value ?: JtxContract.JtxRelatedto.Reltype.PARENT.name

                                // remove the known parameter
                                prop.parameters?.removeAll(RelType.RELTYPE)

                                // save unknown parameters in the other field
                                this.other = JtxContract.getJsonStringFromXParameters(prop.parameters)
                            })
                    }

                    is net.fortuna.ical4j.model.property.Attendee -> {
                        iCalObject.attendees.add(
                            Attendee().apply {
                                this.caladdress = prop.calAddress.toString()
                                this.cn = prop.parameters?.getParameter<Cn>(Parameter.CN)?.value
                                this.delegatedto = prop.parameters?.getParameter<DelegatedTo>(Parameter.DELEGATED_TO)?.value
                                this.delegatedfrom = prop.parameters?.getParameter<DelegatedFrom>(Parameter.DELEGATED_FROM)?.value
                                this.cutype = prop.parameters?.getParameter<CuType>(Parameter.CUTYPE)?.value
                                this.dir = prop.parameters?.getParameter<Dir>(Parameter.DIR)?.value
                                this.language = prop.parameters?.getParameter<Language>(Parameter.LANGUAGE)?.value
                                this.member = prop.parameters?.getParameter<Member>(Parameter.MEMBER)?.value
                                this.partstat = prop.parameters?.getParameter<PartStat>(Parameter.PARTSTAT)?.value
                                this.role = prop.parameters?.getParameter<Role>(Parameter.ROLE)?.value
                                this.rsvp = prop.parameters?.getParameter<Rsvp>(Parameter.RSVP)?.value?.toBoolean()
                                this.sentby = prop.parameters?.getParameter<SentBy>(Parameter.SENT_BY)?.value

                                // remove all known parameters so that only unknown parameters remain
                                prop.parameters?.removeAll(Parameter.CN)
                                prop.parameters?.removeAll(Parameter.DELEGATED_TO)
                                prop.parameters?.removeAll(Parameter.DELEGATED_FROM)
                                prop.parameters?.removeAll(Parameter.CUTYPE)
                                prop.parameters?.removeAll(Parameter.DIR)
                                prop.parameters?.removeAll(Parameter.LANGUAGE)
                                prop.parameters?.removeAll(Parameter.MEMBER)
                                prop.parameters?.removeAll(Parameter.PARTSTAT)
                                prop.parameters?.removeAll(Parameter.ROLE)
                                prop.parameters?.removeAll(Parameter.RSVP)
                                prop.parameters?.removeAll(Parameter.SENT_BY)

                                // save unknown parameters in the other field
                                this.other = JtxContract.getJsonStringFromXParameters(prop.parameters)
                            }
                        )
                    }
                    is net.fortuna.ical4j.model.property.Organizer -> {
                    iCalObject.organizer = Organizer().apply {
                        this.caladdress = prop.calAddress.toString()
                        this.cn = prop.parameters?.getParameter<Cn>(Parameter.CN)?.value
                        this.dir = prop.parameters?.getParameter<Dir>(Parameter.DIR)?.value
                        this.language = prop.parameters?.getParameter<Language>(Parameter.LANGUAGE)?.value
                        this.sentby = prop.parameters?.getParameter<SentBy>(Parameter.SENT_BY)?.value

                        // remove all known parameters so that only unknown parameters remain
                        prop.parameters?.removeAll(Parameter.CN)
                        prop.parameters?.removeAll(Parameter.DIR)
                        prop.parameters?.removeAll(Parameter.LANGUAGE)
                        prop.parameters?.removeAll(Parameter.SENT_BY)

                        // save unknown parameters in the other field
                        this.other = JtxContract.getJsonStringFromXParameters(prop.parameters)
                    }
                }

                    is Uid -> iCalObject.uid = prop.value
                    //is Uid,
                    is ProdId, is DtStamp -> {
                    }    /* don't save these as unknown properties */
                    else -> {
                        if(prop.name == X_PROP_COMPLETEDTIMEZONE)
                            iCalObject.completedTimezone = prop.value
                        else
                            iCalObject.unknown.add(Unknown(value = UnknownProperty.toJsonString(prop)))               // save the whole property for unknown properties
                    }
                }
            }


            // There seem to be many invalid tasks out there because of some defect clients, do some validation.
            val dtStartTZ = iCalObject.dtstartTimezone
            val dueTZ = iCalObject.dueTimezone

            if (dtStartTZ != null && dueTZ != null) {
                if (dtStartTZ == TZ_ALLDAY && dueTZ != TZ_ALLDAY) {
                    Ical4Android.log.warning("DTSTART is DATE but DUE is DATE-TIME, rewriting DTSTART to DATE-TIME")
                    iCalObject.dtstartTimezone = dueTZ
                } else if (dtStartTZ != TZ_ALLDAY && dueTZ == TZ_ALLDAY) {
                    Ical4Android.log.warning("DTSTART is DATE-TIME but DUE is DATE, rewriting DUE to DATE-TIME")
                    iCalObject.dueTimezone = dtStartTZ
                }

                if ( iCalObject.dtstart != null && iCalObject.due != null && iCalObject.due!! <= iCalObject.dtstart!!) {
                    Ical4Android.log.warning("Found invalid DUE <= DTSTART; dropping DUE")     // Dtstart must not be dropped as it might be the basis for recurring tasks
                    iCalObject.due = null
                    iCalObject.dueTimezone = null
                }
            }

            if (iCalObject.duration != null && iCalObject.dtstart == null) {
                Ical4Android.log.warning("Found DURATION without DTSTART; ignoring")
                iCalObject.duration = null
            }
        }
    }

    /**
     * Takes the current JtxICalObject and transforms it to a Calendar (ical4j)
     * @return The current JtxICalObject transformed into a ical4j Calendar
     */
    @UsesThreadContextClassLoader
    fun getICalendarFormat(): Calendar? {
        Ical4Android.checkThreadContextClassLoader()

        val ical = Calendar()
        ical.properties += Version.VERSION_2_0
        ical.properties += ICalendar.prodId

        val calComponent = when (component) {
            JtxContract.JtxICalObject.Component.VTODO.name -> VToDo(true /* generates DTSTAMP */)
            JtxContract.JtxICalObject.Component.VJOURNAL.name -> VJournal(true /* generates DTSTAMP */)
            else -> return null
        }
        ical.components += calComponent
        addProperties(calComponent.properties)

        alarms.forEach { alarm ->

            val vAlarm = VAlarm()
            vAlarm.properties.apply {
                alarm.action?.let {
                    when (it) {
                        JtxContract.JtxAlarm.AlarmAction.DISPLAY.name -> add(Action.DISPLAY)
                        JtxContract.JtxAlarm.AlarmAction.AUDIO.name -> add(Action.AUDIO)
                        JtxContract.JtxAlarm.AlarmAction.EMAIL.name -> add(Action.EMAIL)
                        else -> return@let
                    }
                }
                if(alarm.triggerRelativeDuration != null) {
                    add(Trigger().apply {
                        try {
                            val dur = java.time.Duration.parse(alarm.triggerRelativeDuration)
                            this.duration = dur

                            // Add the RELATED parameter if present
                            alarm.triggerRelativeTo?.let {
                                if(it == JtxContract.JtxAlarm.AlarmRelativeTo.START.name)
                                    this.parameters.add(Related.START)
                                if(it == JtxContract.JtxAlarm.AlarmRelativeTo.END.name)
                                    this.parameters.add(Related.END)
                            }
                        } catch (e: DateTimeParseException) {
                            Ical4Android.log.log(Level.WARNING, "Could not parse Trigger duration as Duration.", e)
                        }
                    })

                } else if (alarm.triggerTime != null) {
                    add(Trigger().apply {
                        try {
                            when {
                                alarm.triggerTimezone == TimeZone.getTimeZone("UTC").id -> this.dateTime = DateTime(alarm.triggerTime!!).apply {
                                    this.isUtc = true
                                }
                                alarm.triggerTimezone.isNullOrEmpty() -> this.dateTime = DateTime(alarm.triggerTime!!).apply {
                                    this.isUtc = true
                                }
                                else -> {
                                    val timezone = TimeZoneRegistryFactory.getInstance().createRegistry()
                                        .getTimeZone(alarm.triggerTimezone)
                                    this.dateTime = DateTime(alarm.triggerTime!!).apply{
                                        this.timeZone = timezone
                                    }
                                }
                            }
                        } catch (e: ParseException) {
                            Ical4Android.log.log(Level.WARNING, "TriggerTime could not be parsed.", e)
                        }})
                }
                alarm.summary?.let { add(Summary(it)) }
                alarm.repeat?.let { add(Repeat().apply { value = it }) }
                alarm.duration?.let { add(Duration().apply {
                    try {
                        val dur = java.time.Duration.parse(it)
                        this.duration = dur
                    } catch (e: DateTimeParseException) {
                        Ical4Android.log.log(Level.WARNING, "Could not parse duration as Duration.", e)
                    }
                }) }
                alarm.description?.let { add(Description(it)) }
                alarm.attach?.let { add(Attach().apply { value = it }) }
                alarm.other?.let { addAll(JtxContract.getXPropertyListFromJson(it)) }

            }
            calComponent.components.add(vAlarm)
        }

        ICalendar.softValidate(ical)
        return ical
    }

    /**
     * Takes the current JtxICalObject, transforms it to an iCalendar and writes it in an OutputStream
     * @param [os] OutputStream where iCalendar should be written to
     */
    @UsesThreadContextClassLoader
    fun write(os: OutputStream) {
        Ical4Android.checkThreadContextClassLoader()
        CalendarOutputter(false).output(this.getICalendarFormat(), os)
    }

    /**
     * This function maps the current JtxICalObject to a iCalendar property list
     * @param [props] The PropertyList where the properties should be added
     */
    private fun addProperties(props: PropertyList<Property>) {

        uid.let { props += Uid(it) }
        sequence.let { props += Sequence(it.toInt()) }

        created.let { props += Created(DateTime(it).apply {
            this.isUtc = true
        }) }
        lastModified.let { props += LastModified(DateTime(it).apply {
            this.isUtc = true
        }) }

        summary.let { props += Summary(it) }
        description?.let { props += Description(it) }

        location?.let { location ->
            val loc = Location(location)
            locationAltrep?.let { locationAltrep ->
                loc.parameters.add(AltRep(locationAltrep))
            }
            props += loc
        }
        if (geoLat != null && geoLong != null) {
            props += Geo(geoLat!!.toBigDecimal(), geoLong!!.toBigDecimal())
        }
        color?.let { props += Color(null, Css3Color.nearestMatch(it).name) }
        url?.let {
            try {
                props += Url(URI(it))
            } catch (e: URISyntaxException) {
                Ical4Android.log.log(Level.WARNING, "Ignoring invalid task URL: $url", e)
            }
        }

        classification?.let { props += Clazz(it) }
        status?.let { props += Status(it) }


        val categoryTextList = TextList()
        categories.forEach {
            categoryTextList.add(it.text)
        }
        if (!categoryTextList.isEmpty)
            props += Categories(categoryTextList)


        val resourceTextList = TextList()
        resources.forEach {
            resourceTextList.add(it.text)
        }
        if (!resourceTextList.isEmpty)
            props += Resources(resourceTextList)


        comments.forEach { comment ->
            val c = Comment(comment.text).apply {
                comment.altrep?.let { this.parameters.add(AltRep(it)) }
                comment.language?.let { this.parameters.add(Language(it)) }
                comment.other?.let {
                    val xparams = JtxContract.getXParametersFromJson(it)
                    xparams.forEach { xparam ->
                        this.parameters.add(xparam)
                    }
                }
            }
            props += c
        }


        attendees.forEach { attendee ->
            val attendeeProp = net.fortuna.ical4j.model.property.Attendee().apply {
                this.calAddress = URI(attendee.caladdress)

                attendee.cn?.let {
                    this.parameters.add(Cn(it))
                }
                attendee.cutype?.let {
                    when {
                        it.equals(CuType.INDIVIDUAL.value, ignoreCase = true) -> this.parameters.add(CuType.INDIVIDUAL)
                        it.equals(CuType.GROUP.value, ignoreCase = true) -> this.parameters.add(CuType.GROUP)
                        it.equals(CuType.ROOM.value, ignoreCase = true) -> this.parameters.add(CuType.ROOM)
                        it.equals(CuType.RESOURCE.value, ignoreCase = true) -> this.parameters.add(CuType.RESOURCE)
                        it.equals(CuType.UNKNOWN.value, ignoreCase = true) -> this.parameters.add(CuType.UNKNOWN)
                        else -> this.parameters.add(CuType.UNKNOWN)
                    }
                }
                attendee.delegatedfrom?.let {
                    this.parameters.add(DelegatedFrom(it))
                }
                attendee.delegatedto?.let {
                    this.parameters.add(DelegatedTo(it))
                }
                attendee.dir?.let {
                    this.parameters.add(Dir(it))
                }
                attendee.language?.let {
                    this.parameters.add(Language(it))
                }
                attendee.member?.let {
                    this.parameters.add(Member(it))
                }
                attendee.partstat?.let {
                    this.parameters.add(PartStat(it))
                }
                attendee.role?.let {
                    this.parameters.add(Role(it))
                }
                attendee.rsvp?.let {
                    this.parameters.add(Rsvp(it))
                }
                attendee.sentby?.let {
                    this.parameters.add(SentBy(it))
                }
                attendee.other?.let {
                    val params = JtxContract.getXParametersFromJson(it)
                    params.forEach { xparam ->
                        this.parameters.add(xparam)
                    }
                }
            }
            props += attendeeProp
        }

        organizer?.let { organizer ->
            val organizerProp = net.fortuna.ical4j.model.property.Organizer().apply {
                if(organizer.caladdress?.isNotEmpty() == true)
                    this.calAddress = URI(organizer.caladdress)

                organizer.cn?.let {
                    this.parameters.add(Cn(it))
                }
                organizer.dir?.let {
                    this.parameters.add(Dir(it))
                }
                organizer.language?.let {
                    this.parameters.add(Language(it))
                }
                organizer.sentby?.let {
                    this.parameters.add(SentBy(it))
                }
                organizer.other?.let {
                    val params = JtxContract.getXParametersFromJson(it)
                    params.forEach { xparam ->
                        this.parameters.add(xparam)
                    }
                }
            }
            props += organizerProp
        }

        attachments.forEach { attachment ->

            try {
                if (attachment.uri?.startsWith("content://") == true) {

                    val attachmentUri = ContentUris.withAppendedId(JtxContract.JtxAttachment.CONTENT_URI.asSyncAdapter(collection.account), attachment.attachmentId)
                    val attachmentFile = collection.client.openFile(attachmentUri, "r")
                    val attachmentBytes = ParcelFileDescriptor.AutoCloseInputStream(attachmentFile).readBytes()
                    if(attachmentBytes.size <= MAX_ATTACHMENT_SYNC_SIZE) {     // Sync only small attachments that are smaller than 100 KB, larger ones are ignored
                        val att = Attach(attachmentBytes).apply {
                            attachment.fmttype?.let { this.parameters.add(FmtType(it)) }
                        }
                        props += att
                    }

                } else {
                    attachment.uri?.let { uri ->
                        val att = Attach(URI(uri)).apply {
                            attachment.fmttype?.let { this.parameters.add(FmtType(it)) }
                        }
                        props += att
                    }
                }
            } catch (e: FileNotFoundException) {
                Ical4Android.log.log(Level.WARNING, "File not found at the given Uri: ${attachment.uri}", e)
            } catch (e: NullPointerException) {
                Ical4Android.log.log(Level.WARNING, "Provided Uri was empty: ${attachment.uri}", e)
            } catch (e: IllegalArgumentException) {
                Ical4Android.log.log(Level.WARNING, "Uri could not be parsed: ${attachment.uri}", e)
            }
        }

        unknown.forEach {
            it.value?.let {  jsonString ->
                props.add(UnknownProperty.fromJsonString(jsonString))
            }
        }

        relatedTo.forEach {
            val param: Parameter =
                when (it.reltype) {
                    RelType.CHILD.value -> RelType.CHILD
                    RelType.SIBLING.value -> RelType.SIBLING
                    RelType.PARENT.value -> RelType.PARENT
                    else -> return@forEach
                }
            val parameterList = ParameterList()
            parameterList.add(param)
            props += RelatedTo(parameterList, it.text)
        }

        dtstart?.let {
            when {
                dtstartTimezone == TZ_ALLDAY -> props += DtStart(Date(it))
                dtstartTimezone == TimeZone.getTimeZone("UTC").id -> props += DtStart(DateTime(it).apply {
                    this.isUtc = true
                })
                dtstartTimezone.isNullOrEmpty() -> props += DtStart(DateTime(it).apply {
                    this.isUtc = false
                })
                else -> {
                    val timezone = TimeZoneRegistryFactory.getInstance().createRegistry()
                        .getTimeZone(dtstartTimezone)
                    val withTimezone = DtStart(DateTime(it))
                    withTimezone.timeZone = timezone
                    props += withTimezone
                }
            }
        }

        rrule?.let { rrule ->
            props += RRule(rrule)
        }
        recurid?.let { recurid ->
            props += RecurrenceId(recurid)
        }

        rdate?.let { rdateString ->

            when {
                dtstartTimezone == TZ_ALLDAY -> {
                    val dateListDate = DateList(Value.DATE)
                    JtxContract.getLongListFromString(rdateString).forEach {
                        dateListDate.add(Date(it))
                    }
                    props += RDate(dateListDate)

                }
                dtstartTimezone == TimeZone.getTimeZone("UTC").id -> {
                    val dateListDateTime = DateList(Value.DATE_TIME)
                    JtxContract.getLongListFromString(rdateString).forEach {
                        dateListDateTime.add(DateTime(it).apply {
                            this.isUtc = true
                        })
                    }
                    props += RDate(dateListDateTime)
                }
                dtstartTimezone.isNullOrEmpty() -> {
                    val dateListDateTime = DateList(Value.DATE_TIME)
                    JtxContract.getLongListFromString(rdateString).forEach {
                        dateListDateTime.add(DateTime(it).apply {
                            this.isUtc = false
                        })
                    }
                    props += RDate(dateListDateTime)
                }
                else -> {
                    val dateListDateTime = DateList(Value.DATE_TIME)
                    val timezone = TimeZoneRegistryFactory.getInstance().createRegistry().getTimeZone(dtstartTimezone)
                    JtxContract.getLongListFromString(rdateString).forEach {
                        val withTimezone = DateTime(it)
                        withTimezone.timeZone = timezone
                        dateListDateTime.add(DateTime(withTimezone))
                    }
                    props += RDate(dateListDateTime)
                }
            }
        }

        exdate?.let { exdateString ->

            when {
                dtstartTimezone == TZ_ALLDAY -> {
                    val dateListDate = DateList(Value.DATE)
                    JtxContract.getLongListFromString(exdateString).forEach {
                        dateListDate.add(Date(it))
                    }
                    props += ExDate(dateListDate)

                }
                dtstartTimezone == TimeZone.getTimeZone("UTC").id -> {
                    val dateListDateTime = DateList(Value.DATE_TIME)
                    JtxContract.getLongListFromString(exdateString).forEach {
                        dateListDateTime.add(DateTime(it).apply {
                            this.isUtc = true
                        })
                    }
                    props += ExDate(dateListDateTime)
                }
                dtstartTimezone.isNullOrEmpty() -> {
                    val dateListDateTime = DateList(Value.DATE_TIME)
                    JtxContract.getLongListFromString(exdateString).forEach {
                        dateListDateTime.add(DateTime(it).apply {
                            this.isUtc = false
                        })
                    }
                    props += ExDate(dateListDateTime)
                }
                else -> {
                    val dateListDateTime = DateList(Value.DATE_TIME)
                    val timezone = TimeZoneRegistryFactory.getInstance().createRegistry().getTimeZone(dtstartTimezone)
                    JtxContract.getLongListFromString(exdateString).forEach {
                        val withTimezone = DateTime(it)
                        withTimezone.timeZone = timezone
                        dateListDateTime.add(DateTime(withTimezone))
                    }
                    props += ExDate(dateListDateTime)
                }
            }
        }

        duration?.let {
            val dur = Duration()
            dur.value = it
            props += dur
        }


        /*
// remember used time zones
val usedTimeZones = HashSet<TimeZone>()
duration?.let(props::add)
*/


        if(component == JtxContract.JtxICalObject.Component.VTODO.name) {
            completed?.let {
                //Completed is defines as always DateTime! And is always UTC! But the X_PROP_COMPLETEDTIMEZONE can still define a timezone
                props += Completed(DateTime(it))

                // only take completedTimezone if there was the completed time set
                completedTimezone?.let { complTZ ->
                    props += XProperty(X_PROP_COMPLETEDTIMEZONE, complTZ)
                }
            }

            percent?.let {
                props += PercentComplete(it)
            }


            if (priority != null && priority != Priority.UNDEFINED.level)
                priority?.let {
                    props += Priority(it)
                }
            else {
                props += Priority(Priority.UNDEFINED.level)
            }

            due?.let {
                when {
                    dueTimezone == TZ_ALLDAY -> props += Due(Date(it))
                    dueTimezone == TimeZone.getTimeZone("UTC").id -> props += Due(DateTime(it).apply {
                    this.isUtc = true
                    })
                    dueTimezone.isNullOrEmpty() -> props += Due(DateTime(it).apply {
                        this.isUtc = false
                    })
                    else -> {
                        val timezone = TimeZoneRegistryFactory.getInstance().createRegistry()
                            .getTimeZone(dueTimezone)
                        val withTimezone = Due(DateTime(it))
                        withTimezone.timeZone = timezone
                        props += withTimezone
                    }
                }
            }
        }

        /*

    // determine earliest referenced date
    val earliest = arrayOf(
        dtStart?.date,
        due?.date,
        completedAt?.date
    ).filterNotNull().min()
    // add VTIMEZONE components
    for (tz in usedTimeZones)
        ical.components += ICalendar.minifyVTimeZone(tz.vTimeZone, earliest)
*/
    }


    fun prepareForUpload(): String {
        return "${this.uid}.ics"
    }

    /**
     * Updates the fileName, eTag and scheduleTag of the current JtxICalObject
     */
    fun clearDirty(fileName: String?, eTag: String?, scheduleTag: String?) {

        var updateUri = JtxContract.JtxICalObject.CONTENT_URI.asSyncAdapter(collection.account)
        updateUri = Uri.withAppendedPath(updateUri, this.id.toString())

        val values = ContentValues()
        fileName?.let { values.put(JtxContract.JtxICalObject.FILENAME, fileName) }
        eTag?.let { values.put(JtxContract.JtxICalObject.ETAG, eTag) }
        scheduleTag?.let { values.put(JtxContract.JtxICalObject.SCHEDULETAG, scheduleTag) }
        values.put(JtxContract.JtxICalObject.DIRTY, false)

        collection.client.update(updateUri, values, null, null)
    }

    /**
     * Updates the flags of the current JtxICalObject
     * @param [flags] to be set as [Int]
     */
    fun updateFlags(flags: Int) {

        var updateUri = JtxContract.JtxICalObject.CONTENT_URI.asSyncAdapter(collection.account)
        updateUri = Uri.withAppendedPath(updateUri, this.id.toString())

        val values = ContentValues()
        values.put(JtxContract.JtxICalObject.FLAGS, flags)

        collection.client.update(updateUri, values, null, null)
    }

    /**
     * adds the current JtxICalObject in the jtx DB through the provider
     * @return the Content [Uri] of the inserted object
     */
    fun add(): Uri {
        val values = this.toContentValues()

        val newUri = collection.client.insert(
            JtxContract.JtxICalObject.CONTENT_URI.asSyncAdapter(collection.account),
            values
        ) ?: return Uri.EMPTY
        this.id = newUri.lastPathSegment?.toLong() ?: return Uri.EMPTY

        insertOrUpdateListProperties(false)

        return newUri
    }

    /**
     * Updates the current JtxICalObject with the given data
     * @param [data] The JtxICalObject with the information that should be applied to this object and updated in the provider
     * @return [Uri] of the updated entry
     */
    fun update(data: JtxICalObject): Uri {

        this.applyNewData(data)
        val values = this.toContentValues()

        var updateUri = JtxContract.JtxICalObject.CONTENT_URI.asSyncAdapter(collection.account)
        updateUri = Uri.withAppendedPath(updateUri, this.id.toString())
        collection.client.update(
            updateUri,
            values,
            "${JtxContract.JtxICalObject.ID} = ?",
            arrayOf(this.id.toString())
        )

        insertOrUpdateListProperties(true)

        return updateUri
    }


    /**
     * This function takes care of all list properties and inserts them in the DB through the provider
     * @param isUpdate if true then the list properties are deleted through the provider before they are inserted
     */
    private fun insertOrUpdateListProperties(isUpdate: Boolean) {

        // delete the categories, attendees, ... and insert them again after. Only relevant for Update, for an insert there will be no entries
        if (isUpdate) {
            collection.client.delete(
                JtxContract.JtxCategory.CONTENT_URI.asSyncAdapter(collection.account),
                "${JtxContract.JtxCategory.ICALOBJECT_ID} = ?",
                arrayOf(this.id.toString())
            )

            collection.client.delete(
                JtxContract.JtxComment.CONTENT_URI.asSyncAdapter(collection.account),
                "${JtxContract.JtxComment.ICALOBJECT_ID} = ?",
                arrayOf(this.id.toString())
            )

            collection.client.delete(
                JtxContract.JtxResource.CONTENT_URI.asSyncAdapter(collection.account),
                "${JtxContract.JtxResource.ICALOBJECT_ID} = ?",
                arrayOf(this.id.toString())
            )

            collection.client.delete(
                JtxContract.JtxRelatedto.CONTENT_URI.asSyncAdapter(collection.account),
                "${JtxContract.JtxRelatedto.ICALOBJECT_ID} = ?",
                arrayOf(this.id.toString())
            )

            collection.client.delete(
                JtxContract.JtxAttendee.CONTENT_URI.asSyncAdapter(collection.account),
                "${JtxContract.JtxAttendee.ICALOBJECT_ID} = ?",
                arrayOf(this.id.toString())
            )

            collection.client.delete(
                JtxContract.JtxOrganizer.CONTENT_URI.asSyncAdapter(collection.account),
                "${JtxContract.JtxOrganizer.ICALOBJECT_ID} = ?",
                arrayOf(this.id.toString())
            )

            collection.client.delete(
                JtxContract.JtxAttachment.CONTENT_URI.asSyncAdapter(collection.account),
                "${JtxContract.JtxAttachment.ICALOBJECT_ID} = ?",
                arrayOf(this.id.toString())
            )

            collection.client.delete(
                JtxContract.JtxAlarm.CONTENT_URI.asSyncAdapter(collection.account),
                "${JtxContract.JtxAlarm.ICALOBJECT_ID} = ?",
                arrayOf(this.id.toString())
            )

            collection.client.delete(
                JtxContract.JtxUnknown.CONTENT_URI.asSyncAdapter(collection.account),
                "${JtxContract.JtxUnknown.ICALOBJECT_ID} = ?",
                arrayOf(this.id.toString())
            )
        }

        this.categories.forEach { category ->
            val categoryContentValues = ContentValues().apply {
                put(JtxContract.JtxCategory.ICALOBJECT_ID, id)
                put(JtxContract.JtxCategory.TEXT, category.text)
                put(JtxContract.JtxCategory.ID, category.categoryId)
                put(JtxContract.JtxCategory.LANGUAGE, category.language)
                put(JtxContract.JtxCategory.OTHER, category.other)
            }
            collection.client.insert(
                JtxContract.JtxCategory.CONTENT_URI.asSyncAdapter(collection.account),
                categoryContentValues
            )
        }

        this.comments.forEach { comment ->
            val commentContentValues = ContentValues().apply {
                put(JtxContract.JtxComment.ICALOBJECT_ID, id)
                put(JtxContract.JtxComment.ID, comment.commentId)
                put(JtxContract.JtxComment.TEXT, comment.text)
                put(JtxContract.JtxComment.LANGUAGE, comment.language)
                put(JtxContract.JtxComment.OTHER, comment.other)
            }
            collection.client.insert(
                JtxContract.JtxComment.CONTENT_URI.asSyncAdapter(collection.account),
                commentContentValues
            )
        }


        this.resources.forEach { resource ->
            val resourceContentValues = ContentValues().apply {
                put(JtxContract.JtxResource.ICALOBJECT_ID, id)
                put(JtxContract.JtxResource.ID, resource.resourceId)
                put(JtxContract.JtxResource.TEXT, resource.text)
                put(JtxContract.JtxResource.LANGUAGE, resource.language)
                put(JtxContract.JtxResource.OTHER, resource.other)
            }
            collection.client.insert(
                JtxContract.JtxResource.CONTENT_URI.asSyncAdapter(collection.account),
                resourceContentValues
            )
        }

        this.relatedTo.forEach { related ->
            val relatedToContentValues = ContentValues().apply {
                put(JtxContract.JtxRelatedto.ICALOBJECT_ID, id)
                put(JtxContract.JtxRelatedto.TEXT, related.text)
                put(JtxContract.JtxRelatedto.RELTYPE, related.reltype)
                put(JtxContract.JtxRelatedto.OTHER, related.other)
            }
            collection.client.insert(
                JtxContract.JtxRelatedto.CONTENT_URI.asSyncAdapter(collection.account),
                relatedToContentValues
            )
        }

        this.attendees.forEach { attendee ->
            val attendeeContentValues = ContentValues().apply {
                put(JtxContract.JtxAttendee.ICALOBJECT_ID, id)
                put(JtxContract.JtxAttendee.CALADDRESS, attendee.caladdress)
                put(JtxContract.JtxAttendee.CN, attendee.cn)
                put(JtxContract.JtxAttendee.CUTYPE, attendee.cutype)
                put(JtxContract.JtxAttendee.DELEGATEDFROM, attendee.delegatedfrom)
                put(JtxContract.JtxAttendee.DELEGATEDTO, attendee.delegatedto)
                put(JtxContract.JtxAttendee.DIR, attendee.dir)
                put(JtxContract.JtxAttendee.LANGUAGE, attendee.language)
                put(JtxContract.JtxAttendee.MEMBER, attendee.member)
                put(JtxContract.JtxAttendee.PARTSTAT, attendee.partstat)
                put(JtxContract.JtxAttendee.ROLE, attendee.role)
                put(JtxContract.JtxAttendee.RSVP, attendee.rsvp)
                put(JtxContract.JtxAttendee.SENTBY, attendee.sentby)
                put(JtxContract.JtxAttendee.OTHER, attendee.other)
            }
            collection.client.insert(
                JtxContract.JtxAttendee.CONTENT_URI.asSyncAdapter(
                    collection.account
                ), attendeeContentValues
            )
        }

        this.organizer.let { organizer ->
            val organizerContentValues = ContentValues().apply {
                put(JtxContract.JtxOrganizer.ICALOBJECT_ID, id)
                put(JtxContract.JtxOrganizer.CALADDRESS, organizer?.caladdress)

                put(JtxContract.JtxOrganizer.CN, organizer?.cn)
                put(JtxContract.JtxOrganizer.DIR, organizer?.dir)
                put(JtxContract.JtxOrganizer.LANGUAGE, organizer?.language)
                put(JtxContract.JtxOrganizer.SENTBY, organizer?.sentby)
                put(JtxContract.JtxOrganizer.OTHER, organizer?.other)
            }
            collection.client.insert(
                JtxContract.JtxOrganizer.CONTENT_URI.asSyncAdapter(
                    collection.account
                ), organizerContentValues
            )
        }

        this.attachments.forEach { attachment ->
            val attachmentContentValues = ContentValues().apply {
                put(JtxContract.JtxAttachment.ICALOBJECT_ID, id)
                put(JtxContract.JtxAttachment.URI, attachment.uri)
                put(JtxContract.JtxAttachment.FMTTYPE, attachment.fmttype)
                put(JtxContract.JtxAttachment.OTHER, attachment.other)
            }
            val newAttachment = collection.client.insert(
                JtxContract.JtxAttachment.CONTENT_URI.asSyncAdapter(
                    collection.account
                ), attachmentContentValues
            )
            if(attachment.uri.isNullOrEmpty() && newAttachment != null) {
                val attachmentPFD = collection.client.openFile(newAttachment, "w")
                ParcelFileDescriptor.AutoCloseOutputStream(attachmentPFD).write(Base64.decode(attachment.binary, Base64.DEFAULT))
            }
        }

        this.alarms.forEach { alarm ->
            val alarmContentValues = ContentValues().apply {
                put(JtxContract.JtxAlarm.ICALOBJECT_ID, id)
                put(JtxContract.JtxAlarm.ACTION, alarm.action)
                put(JtxContract.JtxAlarm.ATTACH, alarm.attach)
                //put(JtxContract.JtxAlarm.ATTENDEE, alarm.attendee)
                put(JtxContract.JtxAlarm.DESCRIPTION, alarm.description)
                put(JtxContract.JtxAlarm.DURATION, alarm.duration)
                put(JtxContract.JtxAlarm.REPEAT, alarm.repeat)
                put(JtxContract.JtxAlarm.SUMMARY, alarm.summary)
                put(JtxContract.JtxAlarm.TRIGGER_RELATIVE_TO, alarm.triggerRelativeTo)
                put(JtxContract.JtxAlarm.TRIGGER_RELATIVE_DURATION, alarm.triggerRelativeDuration)
                put(JtxContract.JtxAlarm.TRIGGER_TIME, alarm.triggerTime)
                put(JtxContract.JtxAlarm.TRIGGER_TIMEZONE, alarm.triggerTimezone)
                put(JtxContract.JtxAlarm.OTHER, alarm.other)
            }
            collection.client.insert(
                JtxContract.JtxAlarm.CONTENT_URI.asSyncAdapter(collection.account),
                alarmContentValues
            )
        }

        this.unknown.forEach { unknown ->
            val unknownContentValues = ContentValues().apply {
                put(JtxContract.JtxUnknown.ICALOBJECT_ID, id)
                put(JtxContract.JtxUnknown.UNKNOWN_VALUE, unknown.value)
            }
            collection.client.insert(
                JtxContract.JtxUnknown.CONTENT_URI.asSyncAdapter(collection.account),
                unknownContentValues
            )
        }
    }

    /**
     * Deletes the current JtxICalObject
     * @return The number of deleted records (should always be 1)
     */
    fun delete(): Int {
        val uri = Uri.withAppendedPath(
            JtxContract.JtxICalObject.CONTENT_URI.asSyncAdapter(collection.account),
            id.toString()
        )
        return collection.client.delete(uri, null, null)
    }


    /**
     * This function is used for empty JtxICalObjects that need new data applied, usually a LocalJtxICalObject.
     * @param [newData], the (local) JtxICalObject that should be mapped onto the given JtxICalObject
     */
    fun applyNewData(newData: JtxICalObject) {

        this.component = newData.component
        this.sequence = newData.sequence
        this.created = newData.created
        this.lastModified = newData.lastModified
        this.summary = newData.summary
        this.description = newData.description
        this.uid = newData.uid

        this.location = newData.location
        this.locationAltrep = newData.locationAltrep
        this.geoLat = newData.geoLat
        this.geoLong = newData.geoLong
        this.percent = newData.percent
        this.classification = newData.classification
        this.status = newData.status
        this.priority = newData.priority

        this.dtstart = newData.dtstart
        this.dtstartTimezone = newData.dtstartTimezone
        this.dtend = newData.dtend
        this.dtendTimezone = newData.dtendTimezone
        this.completed = newData.completed
        this.completedTimezone = newData.completedTimezone
        this.due = newData.due
        this.dueTimezone = newData.dueTimezone
        this.duration = newData.duration

        this.rrule = newData.rrule
        this.rdate = newData.rdate
        this.exdate = newData.exdate
        this.recurid = newData.recurid


        this.categories = newData.categories
        this.comments = newData.comments
        this.resources = newData.resources
        this.relatedTo = newData.relatedTo
        this.attendees = newData.attendees
        this.organizer = newData.organizer
        this.attachments = newData.attachments
        this.alarms = newData.alarms
        this.unknown = newData.unknown
    }

    /**
     * Takes Content Values, applies them on the current JtxICalObject and retrieves all further list properties from the content provier and adds them.
     * @param [values] The Content Values with the information about the JtxICalObject
     */
    fun populateFromContentValues(values: ContentValues) {

            values.getAsLong(JtxContract.JtxICalObject.ID)?.let { id -> this.id = id }

            values.getAsString(JtxContract.JtxICalObject.COMPONENT)?.let { component -> this.component = component }
            values.getAsString(JtxContract.JtxICalObject.SUMMARY)?.let { summary -> this.summary = summary }
            values.getAsString(JtxContract.JtxICalObject.DESCRIPTION)?.let { description -> this.description = description }
            values.getAsLong(JtxContract.JtxICalObject.DTSTART)?.let { dtstart -> this.dtstart = dtstart }
            values.getAsString(JtxContract.JtxICalObject.DTSTART_TIMEZONE)?.let { dtstartTimezone -> this.dtstartTimezone = dtstartTimezone }
            values.getAsLong(JtxContract.JtxICalObject.DTEND)?.let { dtend -> this.dtend = dtend }
            values.getAsString(JtxContract.JtxICalObject.DTEND_TIMEZONE)?.let { dtendTimezone -> this.dtendTimezone = dtendTimezone }
            values.getAsString(JtxContract.JtxICalObject.STATUS)?.let { status -> this.status = status }
            values.getAsString(JtxContract.JtxICalObject.CLASSIFICATION)?.let { classification -> this.classification = classification }
            values.getAsString(JtxContract.JtxICalObject.URL)?.let { url -> this.url = url }
            values.getAsDouble(JtxContract.JtxICalObject.GEO_LAT)?.let { geoLat -> this.geoLat = geoLat }
            values.getAsDouble(JtxContract.JtxICalObject.GEO_LONG)?.let { geoLong -> this.geoLong = geoLong }
            values.getAsString(JtxContract.JtxICalObject.LOCATION)?.let { location -> this.location = location }
            values.getAsString(JtxContract.JtxICalObject.LOCATION_ALTREP)?.let { locationAltrep -> this.locationAltrep = locationAltrep }
            values.getAsInteger(JtxContract.JtxICalObject.PERCENT)?.let { percent -> this.percent = percent }
            values.getAsInteger(JtxContract.JtxICalObject.PRIORITY)?.let { priority -> this.priority = priority }
            values.getAsLong(JtxContract.JtxICalObject.DUE)?.let { due -> this.due = due }
            values.getAsString(JtxContract.JtxICalObject.DUE_TIMEZONE)?.let { dueTimezone -> this.dueTimezone = dueTimezone }
            values.getAsLong(JtxContract.JtxICalObject.COMPLETED)?.let { completed -> this.completed = completed }
            values.getAsString(JtxContract.JtxICalObject.COMPLETED_TIMEZONE)?.let { completedTimezone -> this.completedTimezone = completedTimezone }
            values.getAsString(JtxContract.JtxICalObject.DURATION)?.let { duration -> this.duration = duration }
            values.getAsString(JtxContract.JtxICalObject.UID)?.let { uid -> this.uid = uid }
            values.getAsLong(JtxContract.JtxICalObject.CREATED)?.let { created -> this.created = created }
            values.getAsLong(JtxContract.JtxICalObject.DTSTAMP)?.let { dtstamp -> this.dtstamp = dtstamp }
            values.getAsLong(JtxContract.JtxICalObject.LAST_MODIFIED)?.let { lastModified -> this.lastModified = lastModified }
            values.getAsLong(JtxContract.JtxICalObject.SEQUENCE)?.let { sequence -> this.sequence = sequence }
            values.getAsInteger(JtxContract.JtxICalObject.COLOR)?.let { color -> this.color = color }

            values.getAsString(JtxContract.JtxICalObject.RRULE)?.let { rrule -> this.rrule = rrule }
            values.getAsString(JtxContract.JtxICalObject.EXDATE)?.let { exdate -> this.exdate = exdate }
            values.getAsString(JtxContract.JtxICalObject.RDATE)?.let { rdate -> this.rdate = rdate }
            values.getAsString(JtxContract.JtxICalObject.RECURID)?.let { recurid -> this.recurid = recurid }

            this.collectionId = collection.id
            values.getAsBoolean(JtxContract.JtxICalObject.DIRTY)?.let { dirty -> this.dirty = dirty }
            values.getAsBoolean(JtxContract.JtxICalObject.DELETED)?.let { deleted -> this.deleted = deleted }

            values.getAsString(JtxContract.JtxICalObject.FILENAME)?.let { fileName -> this.fileName = fileName }
            values.getAsString(JtxContract.JtxICalObject.ETAG)?.let { eTag -> this.eTag = eTag }
            values.getAsString(JtxContract.JtxICalObject.SCHEDULETAG)?.let { scheduleTag -> this.scheduleTag = scheduleTag }
            values.getAsInteger(JtxContract.JtxICalObject.FLAGS)?.let { flags -> this.flags = flags }


        // Take care of categories
        val categoriesContentValues = getCategoryContentValues()
        categoriesContentValues.forEach { catValues ->
            val category = Category().apply {
                catValues.getAsLong(JtxContract.JtxCategory.ID)?.let { id -> this.categoryId = id }
                catValues.getAsString(JtxContract.JtxCategory.TEXT)?.let { text -> this.text = text }
                catValues.getAsString(JtxContract.JtxCategory.LANGUAGE)?.let { language -> this.language = language }
                catValues.getAsString(JtxContract.JtxCategory.OTHER)?.let { other -> this.other = other }
            }
            categories.add(category)
        }

        // Take care of comments
        val commentsContentValues = getCommentContentValues()
        commentsContentValues.forEach { commentValues ->
            val comment = Comment().apply {
                commentValues.getAsLong(JtxContract.JtxComment.ID)?.let { id -> this.commentId = id }
                commentValues.getAsString(JtxContract.JtxComment.TEXT)?.let { text -> this.text = text }
                commentValues.getAsString(JtxContract.JtxComment.LANGUAGE)?.let { language -> this.language = language }
                commentValues.getAsString(JtxContract.JtxComment.OTHER)?.let { other -> this.other = other }
            }
            comments.add(comment)
        }

        // Take care of resources
        val resourceContentValues = getResourceContentValues()
        resourceContentValues.forEach { resourceValues ->
            val resource = Resource().apply {
                resourceValues.getAsLong(JtxContract.JtxResource.ID)?.let { id -> this.resourceId = id }
                resourceValues.getAsString(JtxContract.JtxResource.TEXT)?.let { text -> this.text = text }
                resourceValues.getAsString(JtxContract.JtxResource.LANGUAGE)?.let { language -> this.language = language }
                resourceValues.getAsString(JtxContract.JtxResource.OTHER)?.let { other -> this.other = other }
            }
            resources.add(resource)
        }


        // Take care of related-to
        val relatedToContentValues = getRelatedToContentValues()
        relatedToContentValues.forEach { relatedToValues ->
            val relTo = RelatedTo().apply {
                relatedToValues.getAsLong(JtxContract.JtxRelatedto.ID)?.let { id -> this.relatedtoId = id }
                relatedToValues.getAsString(JtxContract.JtxRelatedto.TEXT)?.let { text -> this.text = text }
                relatedToValues.getAsString(JtxContract.JtxRelatedto.RELTYPE)?.let { reltype -> this.reltype = reltype }
                relatedToValues.getAsString(JtxContract.JtxRelatedto.OTHER)?.let { other -> this.other = other }

            }
            relatedTo.add(relTo)
        }


        // Take care of attendees
        val attendeeContentValues = getAttendeesContentValues()
        attendeeContentValues.forEach { attendeeValues ->
            val attendee = Attendee().apply {
                attendeeValues.getAsLong(JtxContract.JtxAttendee.ID)?.let { id -> this.attendeeId = id }
                attendeeValues.getAsString(JtxContract.JtxAttendee.CALADDRESS)?.let { caladdress -> this.caladdress = caladdress }
                attendeeValues.getAsString(JtxContract.JtxAttendee.CUTYPE)?.let { cutype -> this.cutype = cutype }
                attendeeValues.getAsString(JtxContract.JtxAttendee.MEMBER)?.let { member -> this.member = member }
                attendeeValues.getAsString(JtxContract.JtxAttendee.ROLE)?.let { role -> this.role = role }
                attendeeValues.getAsString(JtxContract.JtxAttendee.PARTSTAT)?.let { partstat -> this.partstat = partstat }
                attendeeValues.getAsBoolean(JtxContract.JtxAttendee.RSVP)?.let { rsvp -> this.rsvp = rsvp }
                attendeeValues.getAsString(JtxContract.JtxAttendee.DELEGATEDTO)?.let { delto -> this.delegatedto = delto }
                attendeeValues.getAsString(JtxContract.JtxAttendee.DELEGATEDFROM)?.let { delfrom -> this.delegatedfrom = delfrom }
                attendeeValues.getAsString(JtxContract.JtxAttendee.SENTBY)?.let { sentby -> this.sentby = sentby }
                attendeeValues.getAsString(JtxContract.JtxAttendee.CN)?.let { cn -> this.cn = cn }
                attendeeValues.getAsString(JtxContract.JtxAttendee.DIR)?.let { dir -> this.dir = dir }
                attendeeValues.getAsString(JtxContract.JtxAttendee.LANGUAGE)?.let { lang -> this.language = lang }
                attendeeValues.getAsString(JtxContract.JtxAttendee.OTHER)?.let { other -> this.other = other }

            }
            attendees.add(attendee)
        }

        // Take care of organizer
        val organizerContentValues = getOrganizerContentValues()
        val orgnzr = Organizer().apply {
            organizerId = organizerContentValues?.getAsLong(JtxContract.JtxOrganizer.ID) ?: 0L
            caladdress = organizerContentValues?.getAsString(JtxContract.JtxOrganizer.CALADDRESS)
            sentby = organizerContentValues?.getAsString(JtxContract.JtxOrganizer.SENTBY)
            cn = organizerContentValues?.getAsString(JtxContract.JtxOrganizer.CN)
            dir = organizerContentValues?.getAsString(JtxContract.JtxOrganizer.DIR)
            language = organizerContentValues?.getAsString(JtxContract.JtxOrganizer.LANGUAGE)
            other = organizerContentValues?.getAsString(JtxContract.JtxOrganizer.OTHER)
        }
        if(orgnzr.caladdress?.isNotEmpty() == true)   // we only take the organizer if there was a caladdress (otherwise an empty ORGANIZER is created)
            organizer = orgnzr

        // Take care of attachments
        val attachmentContentValues = getAttachmentsContentValues()
        attachmentContentValues.forEach { attachmentValues ->
            val attachment = Attachment().apply {
                attachmentValues.getAsLong(JtxContract.JtxAttachment.ID)?.let { id -> this.attachmentId = id }
                attachmentValues.getAsString(JtxContract.JtxAttachment.URI)?.let { uri -> this.uri = uri }
                attachmentValues.getAsString(JtxContract.JtxAttachment.BINARY)?.let { value -> this.binary = value }
                attachmentValues.getAsString(JtxContract.JtxAttachment.FMTTYPE)?.let { fmttype -> this.fmttype = fmttype }
                attachmentValues.getAsString(JtxContract.JtxAttachment.OTHER)?.let { other -> this.other = other }

            }
            attachments.add(attachment)
        }

        // Take care of alarms
        val alarmContentValues = getAlarmsContentValues()
        alarmContentValues.forEach { alarmValues ->
            val alarm = Alarm().apply {
                alarmValues.getAsLong(JtxContract.JtxAlarm.ID)?.let { id -> this.alarmId = id }
                alarmValues.getAsString(JtxContract.JtxAlarm.ACTION)?.let { action -> this.action = action }
                alarmValues.getAsString(JtxContract.JtxAlarm.DESCRIPTION)?.let { desc -> this.description = desc }
                alarmValues.getAsLong(JtxContract.JtxAlarm.TRIGGER_TIME)?.let { time -> this.triggerTime = time }
                alarmValues.getAsString(JtxContract.JtxAlarm.TRIGGER_TIMEZONE)?.let { tz -> this.triggerTimezone = tz }
                alarmValues.getAsString(JtxContract.JtxAlarm.TRIGGER_RELATIVE_TO)?.let { relative -> this.triggerRelativeTo = relative }
                alarmValues.getAsString(JtxContract.JtxAlarm.TRIGGER_RELATIVE_DURATION)?.let { duration -> this.triggerRelativeDuration = duration }
                alarmValues.getAsString(JtxContract.JtxAlarm.SUMMARY)?.let { summary -> this.summary = summary }
                alarmValues.getAsString(JtxContract.JtxAlarm.DURATION)?.let { dur -> this.duration = dur }
                alarmValues.getAsString(JtxContract.JtxAlarm.REPEAT)?.let { repeat -> this.repeat = repeat }
                alarmValues.getAsString(JtxContract.JtxAlarm.ATTACH)?.let { attach -> this.attach = attach }
                alarmValues.getAsString(JtxContract.JtxAlarm.OTHER)?.let { other -> this.other = other }
            }
            alarms.add(alarm)
        }

        // Take care of uknown properties
        val unknownContentValues = getUnknownContentValues()
        unknownContentValues.forEach { unknownValues ->
            val unknwn = Unknown().apply {
                unknownValues.getAsLong(JtxContract.JtxUnknown.ID)?.let { id -> this.unknownId = id }
                unknownValues.getAsString(JtxContract.JtxUnknown.UNKNOWN_VALUE)?.let { value -> this.value = value }
            }
            unknown.add(unknwn)
        }
    }

    /**
     * Puts the current JtxICalObjects attributes into Content Values
     * @return The JtxICalObject attributes as [ContentValues] (exluding list properties)
     */
    private fun toContentValues(): ContentValues {

        val values = ContentValues()
        values.put(JtxContract.JtxICalObject.ID, id)
        summary.let { values.put(JtxContract.JtxICalObject.SUMMARY, it)  }
        description.let { values.put(JtxContract.JtxICalObject.DESCRIPTION, it) }
        values.put(JtxContract.JtxICalObject.COMPONENT, component)
        status.let { values.put(JtxContract.JtxICalObject.STATUS, it) }
        classification.let { values.put(JtxContract.JtxICalObject.CLASSIFICATION, it) }
        priority.let { values.put(JtxContract.JtxICalObject.PRIORITY, it) }
        values.put(JtxContract.JtxICalObject.ICALOBJECT_COLLECTIONID, collectionId)
        values.put(JtxContract.JtxICalObject.UID, uid)
        geoLat.let { values.put(JtxContract.JtxICalObject.GEO_LAT, it) }
        geoLong.let { values.put(JtxContract.JtxICalObject.GEO_LONG, it) }
        location.let { values.put(JtxContract.JtxICalObject.LOCATION, it) }
        locationAltrep.let { values.put(JtxContract.JtxICalObject.LOCATION_ALTREP, it) }
        percent.let { values.put(JtxContract.JtxICalObject.PERCENT, it) }
        values.put(JtxContract.JtxICalObject.DTSTAMP, dtstamp)
        dtstart.let { values.put(JtxContract.JtxICalObject.DTSTART, it) }
        dtstartTimezone.let { values.put(JtxContract.JtxICalObject.DTSTART_TIMEZONE, it) }
        dtend.let { values.put(JtxContract.JtxICalObject.DTEND, it) }
        dtendTimezone.let { values.put(JtxContract.JtxICalObject.DTEND_TIMEZONE, it) }
        completed.let { values.put(JtxContract.JtxICalObject.COMPLETED, it) }
        completedTimezone.let { values.put(JtxContract.JtxICalObject.COMPLETED_TIMEZONE, it) }
        due.let { values.put(JtxContract.JtxICalObject.DUE, it) }
        dueTimezone.let { values.put(JtxContract.JtxICalObject.DUE_TIMEZONE, it) }
        duration.let { values.put(JtxContract.JtxICalObject.DURATION, it) }

        rrule.let { values.put(JtxContract.JtxICalObject.RRULE, it) }
        rdate.let { values.put(JtxContract.JtxICalObject.RDATE, it) }
        exdate.let { values.put(JtxContract.JtxICalObject.EXDATE, it) }
        recurid.let { values.put(JtxContract.JtxICalObject.RECURID, it) }

        fileName.let { values.put(JtxContract.JtxICalObject.FILENAME, it) }
        eTag.let { values.put(JtxContract.JtxICalObject.ETAG, it) }
        scheduleTag.let { values.put(JtxContract.JtxICalObject.SCHEDULETAG, it) }
        values.put(JtxContract.JtxICalObject.FLAGS, flags)

        return values
    }


    /**
     * @return The categories of the given JtxICalObject as a list of ContentValues
     */
    private fun getCategoryContentValues(): List<ContentValues> {

        val categoryUrl = JtxContract.JtxCategory.CONTENT_URI.asSyncAdapter(collection.account)
        val categoryValues: MutableList<ContentValues> = mutableListOf()
        collection.client.query(
            categoryUrl,
            null,
            "${JtxContract.JtxCategory.ICALOBJECT_ID} = ?",
            arrayOf(this.id.toString()),
            null
        )?.use { cursor ->
            while (cursor.moveToNext()) {
                categoryValues.add(cursor.toValues())
            }
        }
        return categoryValues
    }


    /**
     * @return The comments of the given JtxICalObject as a list of ContentValues
     */
    private fun getCommentContentValues(): List<ContentValues> {

        val commentUrl = JtxContract.JtxComment.CONTENT_URI.asSyncAdapter(collection.account)
        val commentValues: MutableList<ContentValues> = mutableListOf()
        collection.client.query(
            commentUrl,
            null,
            "${JtxContract.JtxComment.ICALOBJECT_ID} = ?",
            arrayOf(this.id.toString()),
            null
        )?.use { cursor ->
            while (cursor.moveToNext()) {
                commentValues.add(cursor.toValues())
            }
        }
        return commentValues
    }

    /**
     * @return The resources of the given JtxICalObject as a list of ContentValues
     */
    private fun getResourceContentValues(): List<ContentValues> {

        val resourceUrl = JtxContract.JtxResource.CONTENT_URI.asSyncAdapter(collection.account)
        val resourceValues: MutableList<ContentValues> = mutableListOf()
        collection.client.query(
            resourceUrl,
            null,
            "${JtxContract.JtxResource.ICALOBJECT_ID} = ?",
            arrayOf(this.id.toString()),
            null
        )?.use { cursor ->
            while (cursor.moveToNext()) {
                resourceValues.add(cursor.toValues())
            }
        }
        return resourceValues
    }

    /**
     * @return The RelatedTo of the given JtxICalObject as a list of ContentValues
     */
    private fun getRelatedToContentValues(): List<ContentValues> {

        val relatedToUrl = JtxContract.JtxRelatedto.CONTENT_URI.asSyncAdapter(collection.account)
        val relatedToValues: MutableList<ContentValues> = mutableListOf()
        collection.client.query(
            relatedToUrl,
            null,
            "${JtxContract.JtxRelatedto.ICALOBJECT_ID} = ? AND ${JtxContract.JtxRelatedto.RELTYPE} = ?",
            arrayOf(this.id.toString(), JtxContract.JtxRelatedto.Reltype.PARENT.name),
            null
        )?.use { cursor ->
            while (cursor.moveToNext()) {
                relatedToValues.add(cursor.toValues())
            }
        }
        return relatedToValues
    }

    /**
     * @return The attendees of the given JtxICalObject as a list of ContentValues
     */
    private fun getAttendeesContentValues(): List<ContentValues> {

        val attendeesUrl = JtxContract.JtxAttendee.CONTENT_URI.asSyncAdapter(collection.account)
        val attendeesValues: MutableList<ContentValues> = mutableListOf()
        collection.client.query(
            attendeesUrl,
            null,
            "${JtxContract.JtxAttendee.ICALOBJECT_ID} = ?",
            arrayOf(this.id.toString()),
            null
        )?.use { cursor ->
            while (cursor.moveToNext()) {
                attendeesValues.add(cursor.toValues())
            }
        }
        return attendeesValues
    }

    /**
     * @return The organizer of the given JtxICalObject as ContentValues
     */
    private fun getOrganizerContentValues(): ContentValues? {

        val organizerUrl = JtxContract.JtxOrganizer.CONTENT_URI.asSyncAdapter(collection.account)
        collection.client.query(
            organizerUrl,
            null,
            "${JtxContract.JtxOrganizer.ICALOBJECT_ID} = ?",
            arrayOf(this.id.toString()),
            null
        )?.use { cursor ->
            if(cursor.moveToFirst()) {
                return cursor.toValues()
            }
        }
        return null
    }

    /**
     * @return The attachments of the given JtxICalObject as a list of ContentValues
     */
    private fun getAttachmentsContentValues(): List<ContentValues> {

        val attachmentsUrl =
            JtxContract.JtxAttachment.CONTENT_URI.asSyncAdapter(collection.account)
        val attachmentsValues: MutableList<ContentValues> = mutableListOf()
        collection.client.query(
            attachmentsUrl,
            null,
            "${JtxContract.JtxAttachment.ICALOBJECT_ID} = ?",
            arrayOf(this.id.toString()),
            null
        )?.use { cursor ->
            while (cursor.moveToNext()) {
                attachmentsValues.add(cursor.toValues())
            }
        }
        return attachmentsValues
    }

    /**
     * @return The alarms of the given JtxICalObject as a list of ContentValues
     */
    private fun getAlarmsContentValues(): List<ContentValues> {

        val alarmsUrl =
            JtxContract.JtxAlarm.CONTENT_URI.asSyncAdapter(collection.account)
        val alarmValues: MutableList<ContentValues> = mutableListOf()
        collection.client.query(
            alarmsUrl,
            null,
            "${JtxContract.JtxAlarm.ICALOBJECT_ID} = ?",
            arrayOf(this.id.toString()),
            null
        )?.use { cursor ->
            while (cursor.moveToNext()) {
                alarmValues.add(cursor.toValues())
            }
        }
        return alarmValues
    }

    /**
     * @return The unknown properties of the given JtxICalObject as a list of ContentValues
     */
    private fun getUnknownContentValues(): List<ContentValues> {

        val unknownUrl =
            JtxContract.JtxUnknown.CONTENT_URI.asSyncAdapter(collection.account)
        val unknownValues: MutableList<ContentValues> = mutableListOf()
        collection.client.query(
            unknownUrl,
            null,
            "${JtxContract.JtxUnknown.ICALOBJECT_ID} = ?",
            arrayOf(this.id.toString()),
            null
        )?.use { cursor ->
            while (cursor.moveToNext()) {
                unknownValues.add(cursor.toValues())
            }
        }
        return unknownValues
    }
}