summaryrefslogtreecommitdiff
path: root/kcalcore/calendar.cpp
blob: 6c521c95db20e8e3cf601d2690223a510433a6d1 (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
/*
  This file is part of the kcalcore library.

  Copyright (c) 1998 Preston Brown <pbrown@kde.org>
  Copyright (c) 2000-2004 Cornelius Schumacher <schumacher@kde.org>
  Copyright (C) 2003-2004 Reinhold Kainhofer <reinhold@kainhofer.com>
  Copyright (c) 2006 David Jarvie <software@astrojar.org.uk>

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public License
  along with this library; see the file COPYING.LIB.  If not, write to
  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  Boston, MA 02110-1301, USA.
*/
/**
  @file
  This file is part of the API for handling calendar data and
  defines the Calendar class.

  @brief
  Represents the main calendar class.

  @author Preston Brown \<pbrown@kde.org\>
  @author Cornelius Schumacher \<schumacher@kde.org\>
  @author Reinhold Kainhofer \<reinhold@kainhofer.com\>
  @author David Jarvie \<software@astrojar.org.uk\>
*/
#include "calendar.h"
#include "calfilter.h"
#include "icaltimezones.h"
#include "sorting.h"
#include "visitor.h"

#include <KDebug>

extern "C" {
#include <icaltimezone.h>
}

#include <algorithm>  // for std::remove()

using namespace KCalCore;

/**
  Private class that helps to provide binary compatibility between releases.
  @internal
*/
//@cond PRIVATE
class KCalCore::Calendar::Private
{
public:
    Private()
        : mTimeZones(new ICalTimeZones),
          mModified(false),
          mNewObserver(false),
          mObserversEnabled(true),
          mDefaultFilter(new CalFilter),
          batchAddingInProgress(false),
          mDeletionTracking(true)
    {
        // Setup default filter, which does nothing
        mFilter = mDefaultFilter;
        mFilter->setEnabled(false);

        mOwner = Person::Ptr(new Person());
        mOwner->setName(QLatin1String("Unknown Name"));
        mOwner->setEmail(QLatin1String("unknown@nowhere"));
    }

    ~Private()
    {
        delete mTimeZones;
        mTimeZones = 0;
        if (mFilter != mDefaultFilter) {
            delete mFilter;
        }
        delete mDefaultFilter;
    }
    KDateTime::Spec timeZoneIdSpec(const QString &timeZoneId, bool view);

    QString mProductId;
    Person::Ptr mOwner;
    ICalTimeZones *mTimeZones; // collection of time zones used in this calendar
    ICalTimeZone mBuiltInTimeZone;   // cached time zone lookup
    ICalTimeZone mBuiltInViewTimeZone;   // cached viewing time zone lookup
    KDateTime::Spec mTimeSpec;
    mutable KDateTime::Spec mViewTimeSpec;
    bool mModified;
    bool mNewObserver;
    bool mObserversEnabled;
    QList<CalendarObserver*> mObservers;

    CalFilter *mDefaultFilter;
    CalFilter *mFilter;

    // These lists are used to put together related To-dos
    QMultiHash<QString, Incidence::Ptr> mOrphans;
    QMultiHash<QString, Incidence::Ptr> mOrphanUids;

    // Lists for associating incidences to notebooks
    QMultiHash<QString, Incidence::Ptr >mNotebookIncidences;
    QHash<QString, QString>mUidToNotebook;
    QHash<QString, bool>mNotebooks; // name to visibility
    QHash<Incidence::Ptr, bool>mIncidenceVisibility; // incidence -> visibility
    QString mDefaultNotebook; // uid of default notebook
    QMap<QString, Incidence::List > mIncidenceRelations;
    bool batchAddingInProgress;
    bool mDeletionTracking;
};

/**
  Make a QHash::value that returns a QVector.
*/
template <typename K, typename V>
QVector<V> values(const QMultiHash<K,V> &c)
{
    QVector<V> v;
    v.reserve(c.size());
    for (typename QMultiHash<K,V>::const_iterator it = c.begin(), end = c.end(); it != end; ++it) {
        v.push_back(it.value());
    }
    return v;
}

template <typename K, typename V>
QVector<V> values(const QMultiHash<K,V> &c, const K &x)
{
    QVector<V> v;
    typename QMultiHash<K,V>::const_iterator it = c.find(x);
    while (it != c.end() && it.key() == x) {
        v.push_back(it.value());
        ++it;
    }
    return v;
}

/**
  Template for a class that implements a visitor for adding an Incidence
  to a resource supporting addEvent(), addTodo() and addJournal() calls.
*/
template<class T>
class AddVisitor : public Visitor
{
public:
    AddVisitor(T *r) : mResource(r) {}

    bool visit(Event::Ptr e)
    {
        return mResource->addEvent(e);
    }
    bool visit(Todo::Ptr t)
    {
        return mResource->addTodo(t);
    }
    bool visit(Journal::Ptr j)
    {
        return mResource->addJournal(j);
    }
    bool visit(FreeBusy::Ptr)
    {
        return false;
    }

private:
    T *mResource;
};

/**
  Template for a class that implements a visitor for deleting an Incidence
  from a resource supporting deleteEvent(), deleteTodo() and deleteJournal()
  calls.
*/
template<class T>
class DeleteVisitor : public Visitor
{
public:
    DeleteVisitor(T *r) : mResource(r) {}

    bool visit(Event::Ptr e)
    {
        mResource->deleteEvent(e);
        return true;
    }
    bool visit(Todo::Ptr t)
    {
        mResource->deleteTodo(t);
        return true;
    }
    bool visit(Journal::Ptr j)
    {
        mResource->deleteJournal(j);
        return true;
    }
    bool visit(FreeBusy::Ptr)
    {
        return false;
    }

private:
    T *mResource;
};
//@endcond

Calendar::Calendar(const KDateTime::Spec &timeSpec)
    : d(new KCalCore::Calendar::Private)
{
    d->mTimeSpec = timeSpec;
    d->mViewTimeSpec = timeSpec;
}

Calendar::Calendar(const QString &timeZoneId)
    : d(new KCalCore::Calendar::Private)
{
    setTimeZoneId(timeZoneId);
}

Calendar::~Calendar()
{
    delete d;
}

Person::Ptr Calendar::owner() const
{
    return d->mOwner;
}

void Calendar::setOwner(const Person::Ptr &owner)
{
    Q_ASSERT(owner);
    d->mOwner = owner;
    setModified(true);
}

void Calendar::setTimeSpec(const KDateTime::Spec &timeSpec)
{
    d->mTimeSpec = timeSpec;
    d->mBuiltInTimeZone = ICalTimeZone();
    setViewTimeSpec(timeSpec);

    doSetTimeSpec(d->mTimeSpec);
}

KDateTime::Spec Calendar::timeSpec() const
{
    return d->mTimeSpec;
}

void Calendar::setTimeZoneId(const QString &timeZoneId)
{
    d->mTimeSpec = d->timeZoneIdSpec(timeZoneId, false);
    d->mViewTimeSpec = d->mTimeSpec;
    d->mBuiltInViewTimeZone = d->mBuiltInTimeZone;

    doSetTimeSpec(d->mTimeSpec);
}

//@cond PRIVATE
KDateTime::Spec Calendar::Private::timeZoneIdSpec(const QString &timeZoneId,
        bool view)
{
    if (view) {
        mBuiltInViewTimeZone = ICalTimeZone();
    } else {
        mBuiltInTimeZone = ICalTimeZone();
    }
    if (timeZoneId == QLatin1String("UTC")) {
        return KDateTime::UTC;
    }
    ICalTimeZone tz = mTimeZones->zone(timeZoneId);
    if (!tz.isValid()) {
        ICalTimeZoneSource tzsrc;
        tz = tzsrc.parse(icaltimezone_get_builtin_timezone(timeZoneId.toLatin1()));
        if (view) {
            mBuiltInViewTimeZone = tz;
        } else {
            mBuiltInTimeZone = tz;
        }
    }
    if (tz.isValid()) {
        return tz;
    } else {
        return KDateTime::ClockTime;
    }
}
//@endcond

QString Calendar::timeZoneId() const
{
    KTimeZone tz = d->mTimeSpec.timeZone();
    return tz.isValid() ? tz.name() : QString();
}

void Calendar::setViewTimeSpec(const KDateTime::Spec &timeSpec) const
{
    d->mViewTimeSpec = timeSpec;
    d->mBuiltInViewTimeZone = ICalTimeZone();
}

void Calendar::setViewTimeZoneId(const QString &timeZoneId) const
{
    d->mViewTimeSpec = d->timeZoneIdSpec(timeZoneId, true);
}

KDateTime::Spec Calendar::viewTimeSpec() const
{
    return d->mViewTimeSpec;
}

QString Calendar::viewTimeZoneId() const
{
    KTimeZone tz = d->mViewTimeSpec.timeZone();
    return tz.isValid() ? tz.name() : QString();
}

ICalTimeZones *Calendar::timeZones() const
{
    return d->mTimeZones;
}

void Calendar::setTimeZones(ICalTimeZones *zones)
{
    if (!zones) {
        return;
    }

    if (d->mTimeZones && (d->mTimeZones != zones)) {
        delete d->mTimeZones;
        d->mTimeZones = 0;
    }
    d->mTimeZones = zones;
}

void Calendar::shiftTimes(const KDateTime::Spec &oldSpec, const KDateTime::Spec &newSpec)
{
    setTimeSpec(newSpec);

    int i, end;
    Event::List ev = events();
    for (i = 0, end = ev.count();  i < end;  ++i) {
        ev[i]->shiftTimes(oldSpec, newSpec);
    }

    Todo::List to = todos();
    for (i = 0, end = to.count();  i < end;  ++i) {
        to[i]->shiftTimes(oldSpec, newSpec);
    }

    Journal::List jo = journals();
    for (i = 0, end = jo.count();  i < end;  ++i) {
        jo[i]->shiftTimes(oldSpec, newSpec);
    }
}

void Calendar::setFilter(CalFilter *filter)
{
    if (filter) {
        d->mFilter = filter;
    } else {
        d->mFilter = d->mDefaultFilter;
    }
    emit filterChanged();
}

CalFilter *Calendar::filter() const
{
    return d->mFilter;
}

QStringList Calendar::categories() const
{
    Incidence::List rawInc(rawIncidences());
    QStringList cats, thisCats;
    // @TODO: For now just iterate over all incidences. In the future,
    // the list of categories should be built when reading the file.
    for (Incidence::List::ConstIterator i = rawInc.constBegin();
            i != rawInc.constEnd(); ++i) {
        thisCats = (*i)->categories();
        for (QStringList::ConstIterator si = thisCats.constBegin();
                si != thisCats.constEnd(); ++si) {
            if (!cats.contains(*si)) {
                cats.append(*si);
            }
        }
    }
    return cats;
}

Incidence::List Calendar::incidences(const QDate &date) const
{
    return mergeIncidenceList(events(date), todos(date), journals(date));
}

Incidence::List Calendar::incidences() const
{
    return mergeIncidenceList(events(), todos(), journals());
}

Incidence::List Calendar::rawIncidences() const
{
    return mergeIncidenceList(rawEvents(), rawTodos(), rawJournals());
}

Incidence::List Calendar::instances(const Incidence::Ptr &incidence) const
{
    if (incidence) {
        Event::List elist;
        Todo::List tlist;
        Journal::List jlist;

        if (incidence->type() == Incidence::TypeEvent) {
            elist = eventInstances(incidence);
        } else if (incidence->type() == Incidence::TypeTodo) {
            tlist = todoInstances(incidence);
        } else if (incidence->type() == Incidence::TypeJournal) {
            jlist = journalInstances(incidence);
        }
        return mergeIncidenceList(elist, tlist, jlist);
    } else {
        return Incidence::List();
    }
}

Incidence::List Calendar::duplicates(const Incidence::Ptr &incidence)
{
    if (incidence) {
        Incidence::List list;
        Incidence::List vals = values(d->mNotebookIncidences);
        Incidence::List::const_iterator it;
        for (it = vals.constBegin(); it != vals.constEnd(); ++it) {
            if (((incidence->dtStart() == (*it)->dtStart()) ||
                    (!incidence->dtStart().isValid() && !(*it)->dtStart().isValid())) &&
                    (incidence->summary() == (*it)->summary())) {
                list.append(*it);
            }
        }
        return list;
    } else {
        return Incidence::List();
    }
}

bool Calendar::addNotebook(const QString &notebook, bool isVisible)
{
    if (d->mNotebooks.contains(notebook)) {
        return false;
    } else {
        d->mNotebooks.insert(notebook, isVisible);
        return true;
    }
}

bool Calendar::updateNotebook(const QString &notebook, bool isVisible)
{
    if (!d->mNotebooks.contains(notebook)) {
        return false;
    } else {
        d->mNotebooks.insert(notebook, isVisible);
        return true;
    }
}

bool Calendar::deleteNotebook(const QString &notebook)
{
    if (!d->mNotebooks.contains(notebook)) {
        return false;
    } else {
        return d->mNotebooks.remove(notebook);
    }
}

bool Calendar::setDefaultNotebook(const QString &notebook)
{
    if (!d->mNotebooks.contains(notebook)) {
        return false;
    } else {
        d->mDefaultNotebook = notebook;
        return true;
    }
}

QString Calendar::defaultNotebook() const
{
    return d->mDefaultNotebook;
}

bool Calendar::hasValidNotebook(const QString &notebook) const
{
    return d->mNotebooks.contains(notebook);
}

bool Calendar::isVisible(const Incidence::Ptr &incidence) const
{
    if (d->mIncidenceVisibility.contains(incidence)) {
        return d->mIncidenceVisibility[incidence];
    }
    const QString nuid = notebook(incidence);
    bool rv;
    if (d->mNotebooks.contains(nuid)) {
        rv = d->mNotebooks.value(nuid);
    } else {
        // NOTE returns true also for nonexisting notebooks for compatibility
        rv = true;
    }
    d->mIncidenceVisibility[incidence] = rv;
    return rv;
}

void Calendar::clearNotebookAssociations()
{
    d->mNotebookIncidences.clear();
    d->mUidToNotebook.clear();
    d->mIncidenceVisibility.clear();
}

bool Calendar::setNotebook(const Incidence::Ptr &inc, const QString &notebook)
{
    if (!inc) {
        return false;
    }

    if (!notebook.isEmpty() &&
            !incidence(inc->uid(), inc->recurrenceId())) {
        kWarning() << "cannot set notebook until incidence has been added";
        return false;
    }

    if (d->mUidToNotebook.contains(inc->uid())) {
        QString old = d->mUidToNotebook.value(inc->uid());
        if (!old.isEmpty() && notebook != old) {
            if (inc->hasRecurrenceId()) {
                kWarning() << "cannot set notebook for child incidences";
                return false;
            }
            // Move all possible children also.
            Incidence::List list = instances(inc);
            Incidence::List::Iterator it;
            for (it = list.begin(); it != list.end(); ++it) {
                d->mNotebookIncidences.remove(old, *it);
                d->mNotebookIncidences.insert(notebook, *it);
            }
            notifyIncidenceChanged(inc);   // for removing from old notebook
            // don not remove from mUidToNotebook to keep deleted incidences
            d->mNotebookIncidences.remove(old, inc);
        }
    }
    if (!notebook.isEmpty()) {
        d->mUidToNotebook.insert(inc->uid(), notebook);
        d->mNotebookIncidences.insert(notebook, inc);
        kDebug() << "setting notebook" << notebook << "for" << inc->uid();
        notifyIncidenceChanged(inc);   // for inserting into new notebook
    }

    return true;
}

QString Calendar::notebook(const Incidence::Ptr &incidence) const
{
    if (incidence) {
        return d->mUidToNotebook.value(incidence->uid());
    } else {
        return QString();
    }
}

QString Calendar::notebook(const QString &uid) const
{
    return d->mUidToNotebook.value(uid);
}

QStringList Calendar::notebooks() const
{
    return d->mNotebookIncidences.uniqueKeys();
}

Incidence::List Calendar::incidences(const QString &notebook) const
{
    if (notebook.isEmpty()) {
        return values(d->mNotebookIncidences);
    } else {
        return values(d->mNotebookIncidences, notebook);
    }
}

/** static */
Event::List Calendar::sortEvents(const Event::List &eventList,
                                 EventSortField sortField,
                                 SortDirection sortDirection)
{

    if (eventList.isEmpty()) {
        return Event::List();
    }

    Event::List eventListSorted;

    // Notice we alphabetically presort Summaries first.
    // We do this so comparison "ties" stay in a nice order.
    eventListSorted = eventList;
    switch (sortField) {
    case EventSortUnsorted:
        break;

    case EventSortStartDate:
        if (sortDirection == SortDirectionAscending) {
            qSort(eventListSorted.begin(), eventListSorted.end(), Events::startDateLessThan);
        } else {
            qSort(eventListSorted.begin(), eventListSorted.end(), Events::startDateMoreThan);
        }
        break;

    case EventSortEndDate:
        if (sortDirection == SortDirectionAscending) {
            qSort(eventListSorted.begin(), eventListSorted.end(), Events::endDateLessThan);
        } else {
            qSort(eventListSorted.begin(), eventListSorted.end(), Events::endDateMoreThan);
        }
        break;

    case EventSortSummary:
        if (sortDirection == SortDirectionAscending) {
            qSort(eventListSorted.begin(), eventListSorted.end(), Events::summaryLessThan);
        } else {
            qSort(eventListSorted.begin(), eventListSorted.end(), Events::summaryMoreThan);
        }
        break;
    }

    return eventListSorted;

}

Event::List Calendar::events(const QDate &date,
                             const KDateTime::Spec &timeSpec,
                             EventSortField sortField,
                             SortDirection sortDirection) const
{
    Event::List el = rawEventsForDate(date, timeSpec, sortField, sortDirection);
    d->mFilter->apply(&el);
    return el;
}

Event::List Calendar::events(const KDateTime &dt) const
{
    Event::List el = rawEventsForDate(dt);
    d->mFilter->apply(&el);
    return el;
}

Event::List Calendar::events(const QDate &start, const QDate &end,
                             const KDateTime::Spec &timeSpec,
                             bool inclusive) const
{
    Event::List el = rawEvents(start, end, timeSpec, inclusive);
    d->mFilter->apply(&el);
    return el;
}

Event::List Calendar::events(EventSortField sortField,
                             SortDirection sortDirection) const
{
    Event::List el = rawEvents(sortField, sortDirection);
    d->mFilter->apply(&el);
    return el;
}

bool Calendar::addIncidence(const Incidence::Ptr &incidence)
{
    if (!incidence) {
        return false;
    }

    AddVisitor<Calendar> v(this);
    return incidence->accept(v, incidence);
}

bool Calendar::deleteIncidence(const Incidence::Ptr &incidence)
{
    if (!incidence) {
        return false;
    }

    if (beginChange(incidence)) {
        DeleteVisitor<Calendar> v(this);
        const bool result = incidence->accept(v, incidence);
        endChange(incidence);
        return result;
    } else {
        return false;
    }
}

Incidence::Ptr Calendar::createException(const Incidence::Ptr &incidence,
        const KDateTime &recurrenceId,
        bool thisAndFuture)
{
    Q_ASSERT(recurrenceId.isValid());
    if (!incidence || !incidence->recurs() || !recurrenceId.isValid()) {
        return Incidence::Ptr();
    }

    Incidence::Ptr newInc(incidence->clone());
    newInc->setCreated(KDateTime::currentUtcDateTime());
    newInc->setRevision(0);
    //Recurring exceptions are not support for now
    newInc->clearRecurrence();

    newInc->setRecurrenceId(recurrenceId);
    newInc->setThisAndFuture(thisAndFuture);
    newInc->setDtStart(recurrenceId);

    // Calculate and set the new end of the incidence
    KDateTime end = incidence->dateTime(IncidenceBase::RoleEnd);

    if (end.isValid()) {
        if (incidence->dtStart().isDateOnly()) {
            int offset = incidence->dtStart().daysTo(recurrenceId);
            end = end.addDays(offset);
        } else {
            qint64 offset = incidence->dtStart().secsTo_long(recurrenceId);
            end = end.addSecs(offset);
        }
        newInc->setDateTime(end, IncidenceBase::RoleEnd);
    }
    return newInc;
}

// Dissociate a single occurrence or all future occurrences from a recurring
// sequence. The new incidence is returned, but not automatically inserted
// into the calendar, which is left to the calling application.
Incidence::Ptr Calendar::dissociateOccurrence(const Incidence::Ptr &incidence,
        const QDate &date,
        const KDateTime::Spec &spec,
        bool single)
{
    if (!incidence || !incidence->recurs()) {
        return Incidence::Ptr();
    }

    Incidence::Ptr newInc(incidence->clone());
    newInc->recreate();
    // Do not call setRelatedTo() when dissociating recurring to-dos, otherwise the new to-do
    // will appear as a child.  Originally, we planned to set a relation with reltype SIBLING
    // when dissociating to-dos, but currently kcalcore only supports reltype PARENT.
    // We can uncomment the following line when we support the PARENT reltype.
    //newInc->setRelatedTo( incidence );
    Recurrence *recur = newInc->recurrence();
    if (single) {
        recur->clear();
    } else {
        // Adjust the recurrence for the future incidences. In particular adjust
        // the "end after n occurrences" rules! "No end date" and "end by ..."
        // don't need to be modified.
        int duration = recur->duration();
        if (duration > 0) {
            int doneduration = recur->durationTo(date.addDays(-1));
            if (doneduration >= duration) {
                kDebug() << "The dissociated event already occurred more often"
                         << "than it was supposed to ever occur. ERROR!";
                recur->clear();
            } else {
                recur->setDuration(duration - doneduration);
            }
        }
    }
    // Adjust the date of the incidence
    if (incidence->type() == Incidence::TypeEvent) {
        Event::Ptr ev = newInc.staticCast<Event>();
        KDateTime start(ev->dtStart());
        int daysTo = start.toTimeSpec(spec).date().daysTo(date);
        ev->setDtStart(start.addDays(daysTo));
        ev->setDtEnd(ev->dtEnd().addDays(daysTo));
    } else if (incidence->type() == Incidence::TypeTodo) {
        Todo::Ptr td = newInc.staticCast<Todo>();
        bool haveOffset = false;
        int daysTo = 0;
        if (td->hasDueDate()) {
            KDateTime due(td->dtDue());
            daysTo = due.toTimeSpec(spec).date().daysTo(date);
            td->setDtDue(due.addDays(daysTo), true);
            haveOffset = true;
        }
        if (td->hasStartDate()) {
            KDateTime start(td->dtStart());
            if (!haveOffset) {
                daysTo = start.toTimeSpec(spec).date().daysTo(date);
            }
            td->setDtStart(start.addDays(daysTo));
            haveOffset = true;
        }
    }
    recur = incidence->recurrence();
    if (recur) {
        if (single) {
            recur->addExDate(date);
        } else {
            // Make sure the recurrence of the past events ends
            // at the corresponding day
            recur->setEndDate(date.addDays(-1));
        }
    }
    return newInc;
}

Incidence::Ptr Calendar::incidence(const QString &uid,
                                   const KDateTime &recurrenceId) const
{
    Incidence::Ptr i = event(uid, recurrenceId);
    if (i) {
        return i;
    }

    i = todo(uid, recurrenceId);
    if (i) {
        return i;
    }

    i = journal(uid, recurrenceId);
    return i;
}

Incidence::Ptr Calendar::deleted(const QString &uid, const KDateTime &recurrenceId) const
{
    Incidence::Ptr i = deletedEvent(uid, recurrenceId);
    if (i) {
        return i;
    }

    i = deletedTodo(uid, recurrenceId);
    if (i) {
        return i;
    }

    i = deletedJournal(uid, recurrenceId);
    return i;
}

Incidence::List Calendar::incidencesFromSchedulingID(const QString &sid) const
{
    Incidence::List result;
    const Incidence::List incidences = rawIncidences();
    Incidence::List::const_iterator it = incidences.begin();
    for (; it != incidences.end(); ++it) {
        if ((*it)->schedulingID() == sid) {
            result.append(*it);
        }
    }
    return result;
}

Incidence::Ptr Calendar::incidenceFromSchedulingID(const QString &uid) const
{
    const Incidence::List incidences = rawIncidences();
    Incidence::List::const_iterator it = incidences.begin();
    for (; it != incidences.end(); ++it) {
        if ((*it)->schedulingID() == uid) {
            // Touchdown, and the crowd goes wild
            return *it;
        }
    }
    // Not found
    return Incidence::Ptr();
}

/** static */
Todo::List Calendar::sortTodos(const Todo::List &todoList,
                               TodoSortField sortField,
                               SortDirection sortDirection)
{
    if (todoList.isEmpty()) {
        return Todo::List();
    }

    Todo::List todoListSorted;

    // Notice we alphabetically presort Summaries first.
    // We do this so comparison "ties" stay in a nice order.

    // Note that To-dos may not have Start DateTimes nor due DateTimes.

    todoListSorted = todoList;
    switch (sortField) {
    case TodoSortUnsorted:
        break;

    case TodoSortStartDate:
        if (sortDirection == SortDirectionAscending) {
            qSort(todoListSorted.begin(), todoListSorted.end(), Todos::startDateLessThan);
        } else {
            qSort(todoListSorted.begin(), todoListSorted.end(), Todos::startDateMoreThan);
        }
        break;

    case TodoSortDueDate:
        if (sortDirection == SortDirectionAscending) {
            qSort(todoListSorted.begin(), todoListSorted.end(), Todos::dueDateLessThan);
        } else {
            qSort(todoListSorted.begin(), todoListSorted.end(), Todos::dueDateMoreThan);
        }
        break;

    case TodoSortPriority:
        if (sortDirection == SortDirectionAscending) {
            qSort(todoListSorted.begin(), todoListSorted.end(), Todos::priorityLessThan);
        } else {
            qSort(todoListSorted.begin(), todoListSorted.end(), Todos::priorityMoreThan);
        }
        break;

    case TodoSortPercentComplete:
        if (sortDirection == SortDirectionAscending) {
            qSort(todoListSorted.begin(), todoListSorted.end(), Todos::percentLessThan);
        } else {
            qSort(todoListSorted.begin(), todoListSorted.end(), Todos::percentMoreThan);
        }
        break;

    case TodoSortSummary:
        if (sortDirection == SortDirectionAscending) {
            qSort(todoListSorted.begin(), todoListSorted.end(), Todos::summaryLessThan);
        } else {
            qSort(todoListSorted.begin(), todoListSorted.end(), Todos::summaryMoreThan);
        }
        break;

    case TodoSortCreated:
        if (sortDirection == SortDirectionAscending) {
            qSort(todoListSorted.begin(), todoListSorted.end(), Todos::createdLessThan);
        } else {
            qSort(todoListSorted.begin(), todoListSorted.end(), Todos::createdMoreThan);
        }
        break;
    }

    return todoListSorted;
}

Todo::List Calendar::todos(TodoSortField sortField,
                           SortDirection sortDirection) const
{
    Todo::List tl = rawTodos(sortField, sortDirection);
    d->mFilter->apply(&tl);
    return tl;
}

Todo::List Calendar::todos(const QDate &date) const
{
    Todo::List el = rawTodosForDate(date);
    d->mFilter->apply(&el);
    return el;
}

Todo::List Calendar::todos(const QDate &start, const QDate &end,
                           const KDateTime::Spec &timespec, bool inclusive) const
{
    Todo::List tl = rawTodos(start, end, timespec, inclusive);
    d->mFilter->apply(&tl);
    return tl;
}

/** static */
Journal::List Calendar::sortJournals(const Journal::List &journalList,
                                     JournalSortField sortField,
                                     SortDirection sortDirection)
{
    if (journalList.isEmpty()) {
        return Journal::List();
    }

    Journal::List journalListSorted = journalList;

    switch (sortField) {
    case JournalSortUnsorted:
        break;

    case JournalSortDate:
        if (sortDirection == SortDirectionAscending) {
            qSort(journalListSorted.begin(), journalListSorted.end(), Journals::dateLessThan);
        } else {
            qSort(journalListSorted.begin(), journalListSorted.end(), Journals::dateMoreThan);
        }
        break;

    case JournalSortSummary:
        if (sortDirection == SortDirectionAscending) {
            qSort(journalListSorted.begin(), journalListSorted.end(), Journals::summaryLessThan);
        } else {
            qSort(journalListSorted.begin(), journalListSorted.end(), Journals::summaryMoreThan);
        }
        break;
    }

    return journalListSorted;
}

Journal::List Calendar::journals(JournalSortField sortField,
                                 SortDirection sortDirection) const
{
    Journal::List jl = rawJournals(sortField, sortDirection);
    d->mFilter->apply(&jl);
    return jl;
}

Journal::List Calendar::journals(const QDate &date) const
{
    Journal::List el = rawJournalsForDate(date);
    d->mFilter->apply(&el);
    return el;
}

// When this is called, the to-dos have already been added to the calendar.
// This method is only about linking related to-dos.
void Calendar::setupRelations(const Incidence::Ptr &forincidence)
{
    if (!forincidence) {
        return;
    }

    const QString uid = forincidence->uid();

    // First, go over the list of orphans and see if this is their parent
    Incidence::List l = values(d->mOrphans, uid);
    d->mOrphans.remove(uid);
    for (int i = 0, end = l.count();  i < end;  ++i) {
        d->mIncidenceRelations[uid].append(l[i]);
        d->mOrphanUids.remove(l[i]->uid());
    }

    // Now see about this incidences parent
    if (forincidence->relatedTo().isEmpty() && !forincidence->relatedTo().isEmpty()) {
        // Incidence has a uid it is related to but is not registered to it yet.
        // Try to find it
        Incidence::Ptr parent = incidence(forincidence->relatedTo());
        if (parent) {
            // Found it

            // look for hierarchy loops
            if (isAncestorOf(forincidence, parent)) {
                forincidence->setRelatedTo(QString());
                kWarning() << "hierarchy loop beetween " << forincidence->uid() << " and " << parent->uid();
            } else {
                d->mIncidenceRelations[parent->uid()].append(forincidence);
            }
        } else {
            // Not found, put this in the mOrphans list
            // Note that the mOrphans dict might contain multiple entries with the
            // same key! which are multiple children that wait for the parent
            // incidence to be inserted.
            d->mOrphans.insert(forincidence->relatedTo(), forincidence);
            d->mOrphanUids.insert(forincidence->uid(), forincidence);
        }
    }
}

// If a to-do with sub-to-dos is deleted, move it's sub-to-dos to the orphan list
void Calendar::removeRelations(const Incidence::Ptr &incidence)
{
    if (!incidence) {
        kDebug() << "Warning: incidence is 0";
        return;
    }

    const QString uid = incidence->uid();

    foreach(Incidence::Ptr i, d->mIncidenceRelations[uid]) {
        if (!d->mOrphanUids.contains(i->uid())) {
            d->mOrphans.insert(uid, i);
            d->mOrphanUids.insert(i->uid(), i);
            i->setRelatedTo(uid);
        }
    }

    const QString parentUid = incidence->relatedTo();

    // If this incidence is related to something else, tell that about it
    if (!parentUid.isEmpty()) {
        d->mIncidenceRelations[parentUid].erase(
            std::remove(d->mIncidenceRelations[parentUid].begin(),
                        d->mIncidenceRelations[parentUid].end(), incidence),
            d->mIncidenceRelations[parentUid].end());
    }

    // Remove this one from the orphans list
    if (d->mOrphanUids.remove(uid)) {
        // This incidence is located in the orphans list - it should be removed
        // Since the mOrphans dict might contain the same key (with different
        // child incidence pointers!) multiple times, take care that we remove
        // the correct one. So we need to remove all items with the given
        // parent UID, and readd those that are not for this item. Also, there
        // might be other entries with differnet UID that point to this
        // incidence (this might happen when the relatedTo of the item is
        // changed before its parent is inserted. This might happen with
        // groupware servers....). Remove them, too
        QStringList relatedToUids;

        // First, create a list of all keys in the mOrphans list which point
        // to the removed item
        relatedToUids << incidence->relatedTo();
        for (QMultiHash<QString, Incidence::Ptr>::Iterator it = d->mOrphans.begin();
                it != d->mOrphans.end(); ++it) {
            if (it.value()->uid() == uid) {
                relatedToUids << it.key();
            }
        }

        // now go through all uids that have one entry that point to the incidence
        for (QStringList::const_iterator uidit = relatedToUids.constBegin();
                uidit != relatedToUids.constEnd(); ++uidit) {
            Incidence::List tempList;
            // Remove all to get access to the remaining entries
            QList<Incidence::Ptr> l = d->mOrphans.values(*uidit);
            d->mOrphans.remove(*uidit);
            foreach(Incidence::Ptr i, l) {
                if (i != incidence) {
                    tempList.append(i);
                }
            }
            // Readd those that point to a different orphan incidence
            for (Incidence::List::Iterator incit = tempList.begin();
                    incit != tempList.end(); ++incit) {
                d->mOrphans.insert(*uidit, *incit);
            }
        }
    }

    // Make sure the deleted incidence doesn't relate to a non-deleted incidence,
    // since that would cause trouble in MemoryCalendar::close(), as the deleted
    // incidences are destroyed after the non-deleted incidences. The destructor
    // of the deleted incidences would then try to access the already destroyed
    // non-deleted incidence, which would segfault.
    //
    // So in short: Make sure dead incidences don't point to alive incidences
    // via the relation.
    //
    // This crash is tested in MemoryCalendarTest::testRelationsCrash().
//  incidence->setRelatedTo( Incidence::Ptr() );
}

bool Calendar::isAncestorOf(const Incidence::Ptr &ancestor,
                            const Incidence::Ptr &incidence) const
{
    if (!incidence || incidence->relatedTo().isEmpty()) {
        return false;
    } else if (incidence->relatedTo() == ancestor->uid()) {
        return true;
    } else {
        return isAncestorOf(ancestor, this->incidence(incidence->relatedTo()));
    }
}

Incidence::List Calendar::relations(const QString &uid) const
{
    return d->mIncidenceRelations[uid];
}

Calendar::CalendarObserver::~CalendarObserver()
{
}

void Calendar::CalendarObserver::calendarModified(bool modified, Calendar *calendar)
{
    Q_UNUSED(modified);
    Q_UNUSED(calendar);
}

void Calendar::CalendarObserver::calendarIncidenceAdded(const Incidence::Ptr &incidence)
{
    Q_UNUSED(incidence);
}

void Calendar::CalendarObserver::calendarIncidenceChanged(const Incidence::Ptr &incidence)
{
    Q_UNUSED(incidence);
}

void Calendar::CalendarObserver::calendarIncidenceDeleted(const Incidence::Ptr &incidence)
{
    Q_UNUSED(incidence);
}

void
Calendar::CalendarObserver::calendarIncidenceAdditionCanceled(const Incidence::Ptr &incidence)
{
    Q_UNUSED(incidence);
}

void Calendar::registerObserver(CalendarObserver *observer)
{
    if (!observer) {
        return;
    }

    if (!d->mObservers.contains(observer)) {
        d->mObservers.append(observer);
    } else {
        d->mNewObserver = true;
    }
}

void Calendar::unregisterObserver(CalendarObserver *observer)
{
    if (!observer) {
        return;
    } else {
        d->mObservers.removeAll(observer);
    }
}

bool Calendar::isSaving() const
{
    return false;
}

void Calendar::setModified(bool modified)
{
    if (modified != d->mModified || d->mNewObserver) {
        d->mNewObserver = false;
        foreach(CalendarObserver *observer, d->mObservers) {
            observer->calendarModified(modified, this);
        }
        d->mModified = modified;
    }
}

bool Calendar::isModified() const
{
    return d->mModified;
}

bool Calendar::save()
{
    return true;
}

bool Calendar::reload()
{
    return true;
}

void Calendar::incidenceUpdated(const QString &uid, const KDateTime &recurrenceId)
{

    Incidence::Ptr inc = incidence(uid, recurrenceId);

    if (!inc) {
        return;
    }

    inc->setLastModified(KDateTime::currentUtcDateTime());
    // we should probably update the revision number here,
    // or internally in the Event itself when certain things change.
    // need to verify with ical documentation.

    notifyIncidenceChanged(inc);

    setModified(true);
}

void Calendar::doSetTimeSpec(const KDateTime::Spec &timeSpec)
{
    Q_UNUSED(timeSpec);
}

void Calendar::notifyIncidenceAdded(const Incidence::Ptr &incidence)
{
    if (!incidence) {
        return;
    }

    if (!d->mObserversEnabled) {
        return;
    }

    foreach(CalendarObserver *observer, d->mObservers) {
        observer->calendarIncidenceAdded(incidence);
    }
}

void Calendar::notifyIncidenceChanged(const Incidence::Ptr &incidence)
{
    if (!incidence) {
        return;
    }

    if (!d->mObserversEnabled) {
        return;
    }

    foreach(CalendarObserver *observer, d->mObservers) {
        observer->calendarIncidenceChanged(incidence);
    }
}

void Calendar::notifyIncidenceDeleted(const Incidence::Ptr &incidence)
{
    if (!incidence) {
        return;
    }

    if (!d->mObserversEnabled) {
        return;
    }

    foreach(CalendarObserver *observer, d->mObservers) {
        observer->calendarIncidenceDeleted(incidence);
    }
}

void Calendar::notifyIncidenceAdditionCanceled(const Incidence::Ptr &incidence)
{
    if (!incidence) {
        return;
    }

    if (!d->mObserversEnabled) {
        return;
    }

    foreach(CalendarObserver *observer, d->mObservers) {
        observer->calendarIncidenceAdditionCanceled(incidence);
    }
}

void Calendar::customPropertyUpdated()
{
    setModified(true);
}

void Calendar::setProductId(const QString &id)
{
    d->mProductId = id;
}

QString Calendar::productId() const
{
    return d->mProductId;
}

/** static */
Incidence::List Calendar::mergeIncidenceList(const Event::List &events,
        const Todo::List &todos,
        const Journal::List &journals)
{
    Incidence::List incidences;

    int i, end;
    for (i = 0, end = events.count();  i < end;  ++i) {
        incidences.append(events[i]);
    }

    for (i = 0, end = todos.count();  i < end;  ++i) {
        incidences.append(todos[i]);
    }

    for (i = 0, end = journals.count();  i < end;  ++i) {
        incidences.append(journals[i]);
    }

    return incidences;
}

bool Calendar::beginChange(const Incidence::Ptr &incidence)
{
    Q_UNUSED(incidence);
    return true;
}

bool Calendar::endChange(const Incidence::Ptr &incidence)
{
    Q_UNUSED(incidence);
    return true;
}

void Calendar::setObserversEnabled(bool enabled)
{
    d->mObserversEnabled = enabled;
}

void Calendar::appendAlarms(Alarm::List &alarms, const Incidence::Ptr &incidence,
                            const KDateTime &from, const KDateTime &to) const
{
    KDateTime preTime = from.addSecs(-1);

    Alarm::List alarmlist = incidence->alarms();
    for (int i = 0, iend = alarmlist.count();  i < iend;  ++i) {
        if (alarmlist[i]->enabled()) {
            KDateTime dt = alarmlist[i]->nextRepetition(preTime);
            if (dt.isValid() && dt <= to) {
                kDebug() << incidence->summary() << "':" << dt.toString();
                alarms.append(alarmlist[i]);
            }
        }
    }
}

void Calendar::appendRecurringAlarms(Alarm::List &alarms,
                                     const Incidence::Ptr &incidence,
                                     const KDateTime &from,
                                     const KDateTime &to) const
{
    KDateTime dt;
    bool endOffsetValid = false;
    Duration endOffset(0);
    Duration period(from, to);

    Alarm::List alarmlist = incidence->alarms();
    for (int i = 0, iend = alarmlist.count();  i < iend;  ++i) {
        Alarm::Ptr a = alarmlist[i];
        if (a->enabled()) {
            if (a->hasTime()) {
                // The alarm time is defined as an absolute date/time
                dt = a->nextRepetition(from.addSecs(-1));
                if (!dt.isValid() || dt > to) {
                    continue;
                }
            } else {
                // Alarm time is defined by an offset from the event start or end time.
                // Find the offset from the event start time, which is also used as the
                // offset from the recurrence time.
                Duration offset(0);
                if (a->hasStartOffset()) {
                    offset = a->startOffset();
                } else if (a->hasEndOffset()) {
                    offset = a->endOffset();
                    if (!endOffsetValid) {
                        endOffset = Duration(incidence->dtStart(),
                                             incidence->dateTime(Incidence::RoleAlarmEndOffset));
                        endOffsetValid = true;
                    }
                }

                // Find the incidence's earliest alarm
                KDateTime alarmStart =
                    offset.end(a->hasEndOffset() ? incidence->dateTime(Incidence::RoleAlarmEndOffset) :
                               incidence->dtStart());
//        KDateTime alarmStart = incidence->dtStart().addSecs( offset );
                if (alarmStart > to) {
                    continue;
                }
                KDateTime baseStart = incidence->dtStart();
                if (from > alarmStart) {
                    alarmStart = from;   // don't look earlier than the earliest alarm
                    baseStart = (-offset).end((-endOffset).end(alarmStart));
                }

                // Adjust the 'alarmStart' date/time and find the next recurrence at or after it.
                // Treate the two offsets separately in case one is daily and the other not.
                dt = incidence->recurrence()->getNextDateTime(baseStart.addSecs(-1));
                if (!dt.isValid() ||
                        (dt = endOffset.end(offset.end(dt))) > to)        // adjust 'dt' to get the alarm time
                {
                    // The next recurrence is too late.
                    if (!a->repeatCount()) {
                        continue;
                    }

                    // The alarm has repetitions, so check whether repetitions of previous
                    // recurrences fall within the time period.
                    bool found = false;
                    Duration alarmDuration = a->duration();
                    for (KDateTime base = baseStart;
                            (dt = incidence->recurrence()->getPreviousDateTime(base)).isValid();
                            base = dt) {
                        if (a->duration().end(dt) < base) {
                            break;  // this recurrence's last repetition is too early, so give up
                        }

                        // The last repetition of this recurrence is at or after 'alarmStart' time.
                        // Check if a repetition occurs between 'alarmStart' and 'to'.
                        int snooze = a->snoozeTime().value();   // in seconds or days
                        if (a->snoozeTime().isDaily()) {
                            Duration toFromDuration(dt, base);
                            int toFrom = toFromDuration.asDays();
                            if (a->snoozeTime().end(from) <= to ||
                                    (toFromDuration.isDaily() && toFrom % snooze == 0) ||
                                    (toFrom / snooze + 1) * snooze <= toFrom + period.asDays()) {
                                found = true;
#ifndef NDEBUG
                                // for debug output
                                dt = offset.end(dt).addDays(((toFrom - 1) / snooze + 1) * snooze);
#endif
                                break;
                            }
                        } else {
                            int toFrom = dt.secsTo(base);
                            if (period.asSeconds() >= snooze ||
                                    toFrom % snooze == 0 ||
                                    (toFrom / snooze + 1) * snooze <= toFrom + period.asSeconds())
                            {
                                found = true;
#ifndef NDEBUG
                                // for debug output
                                dt = offset.end(dt).addSecs(((toFrom - 1) / snooze + 1) * snooze);
#endif
                                break;
                            }
                        }
                    }
                    if (!found) {
                        continue;
                    }
                }
            }
            kDebug() << incidence->summary() << "':" << dt.toString();
            alarms.append(a);
        }
    }
}

void Calendar::startBatchAdding()
{
    d->batchAddingInProgress = true;
}

void Calendar::endBatchAdding()
{
    d->batchAddingInProgress = false;
}

bool Calendar::batchAdding() const
{
    return d->batchAddingInProgress;
}

void Calendar::setDeletionTracking(bool enable)
{
    d->mDeletionTracking = enable;
}

bool Calendar::deletionTracking() const
{
    return d->mDeletionTracking;
}

void Calendar::virtual_hook(int id, void *data)
{
    Q_UNUSED(id);
    Q_UNUSED(data);
    Q_ASSERT(false);
}