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

// user includes
#include "qorganizersymbian_p.h"
#include "qtorganizer.h"
#include "organizeritemtypetransform.h"
#include "organizeritemguidtransform.h"
#include "qorganizeritemrequestqueue.h"
#include "organizersymbianutils.h"
#include "resetanddestroy.h"

using namespace OrganizerSymbianUtils;

QOrganizerItemSymbianEngineId::QOrganizerItemSymbianEngineId()
    : QOrganizerItemEngineId(), m_localCollectionId(0), m_localItemId(0)
{
}

QOrganizerItemSymbianEngineId::QOrganizerItemSymbianEngineId(quint64 collectionId, quint32 itemId)
    : QOrganizerItemEngineId(), m_localCollectionId(collectionId), m_localItemId(itemId)
{
}

QOrganizerItemSymbianEngineId::~QOrganizerItemSymbianEngineId()
{
}

QOrganizerItemSymbianEngineId::QOrganizerItemSymbianEngineId(const QOrganizerItemSymbianEngineId& other)
    : QOrganizerItemEngineId(), m_localCollectionId(other.m_localCollectionId), m_localItemId(other.m_localItemId)
{
}

bool QOrganizerItemSymbianEngineId::isEqualTo(const QOrganizerItemEngineId* other) const
{
    quint64 otherlocalCollectionId = static_cast<const QOrganizerItemSymbianEngineId*>(other)->m_localCollectionId;
    quint32 otherlocalItemId = static_cast<const QOrganizerItemSymbianEngineId*>(other)->m_localItemId;
    if (m_localCollectionId != otherlocalCollectionId)
        return false;
    if (m_localItemId != otherlocalItemId)
        return false;
    return true;
}

bool QOrganizerItemSymbianEngineId::isLessThan(const QOrganizerItemEngineId* other) const
{
    // order by collection, then by item in collection.
    quint64 otherlocalCollectionId = static_cast<const QOrganizerItemSymbianEngineId*>(other)->m_localCollectionId;
    quint32 otherlocalItemId = static_cast<const QOrganizerItemSymbianEngineId*>(other)->m_localItemId;
    if (m_localCollectionId < otherlocalCollectionId)
        return true;
    if (m_localCollectionId == otherlocalCollectionId)
        return (m_localItemId < otherlocalItemId);
    return false;
}

QString QOrganizerItemSymbianEngineId::managerUri() const
{
    // TODO: make this return the actual managerUri (including params) of the
    // engine it is associated with
    static const QString managerUri(QLatin1String("qtorganizer:symbian:"));
    return managerUri;
}

QOrganizerItemEngineId* QOrganizerItemSymbianEngineId::clone() const
{
    QOrganizerItemSymbianEngineId *myClone = new QOrganizerItemSymbianEngineId;
    myClone->m_localCollectionId = m_localCollectionId;
    myClone->m_localItemId = m_localItemId;
    return myClone;
}

QString QOrganizerItemSymbianEngineId::toString() const
{
    return QString::fromAscii("%1:%2").arg(m_localCollectionId).arg(m_localItemId);
}

#ifndef QT_NO_DEBUG_STREAM
QDebug& QOrganizerItemSymbianEngineId::debugStreamOut(QDebug& dbg) const
{
    dbg.nospace() << "QOrganizerItemSymbianEngineId(" << m_localCollectionId << ", " << m_localItemId << ")";
    return dbg.maybeSpace();
}
#endif

uint QOrganizerItemSymbianEngineId::hash() const
{
    // Note: doesn't need to be unique, since == ensures difference.
    // hash function merely determines distribution in a hash table.
    // TODO: collection id is 64 bit
    quint32 combinedLocalId = m_localItemId;
    combinedLocalId <<= 32;
    combinedLocalId += m_localCollectionId;
    return uint(((combinedLocalId >> (8 * sizeof(uint) - 1)) ^ combinedLocalId) & (~0U));
}

QOrganizerCollectionSymbianEngineId::QOrganizerCollectionSymbianEngineId()
    : QOrganizerCollectionEngineId(), m_localCollectionId(0)
{
}

QOrganizerCollectionSymbianEngineId::QOrganizerCollectionSymbianEngineId(quint64 collectionId)
    : QOrganizerCollectionEngineId(), m_localCollectionId(collectionId)
{
}

QOrganizerCollectionSymbianEngineId::QOrganizerCollectionSymbianEngineId(const QOrganizerCollectionSymbianEngineId& other)
    : QOrganizerCollectionEngineId(), m_localCollectionId(other.m_localCollectionId)
{
}

QOrganizerCollectionSymbianEngineId::~QOrganizerCollectionSymbianEngineId()
{
}

bool QOrganizerCollectionSymbianEngineId::isEqualTo(const QOrganizerCollectionEngineId* other) const
{
    quint64 otherlocalCollectionId = static_cast<const QOrganizerCollectionSymbianEngineId*>(other)->m_localCollectionId;
    if (m_localCollectionId != otherlocalCollectionId)
        return false;
    return true;
}

bool QOrganizerCollectionSymbianEngineId::isLessThan(const QOrganizerCollectionEngineId* other) const
{
    // order by collection, then by item in collection.
    quint64 otherlocalCollectionId = static_cast<const QOrganizerCollectionSymbianEngineId*>(other)->m_localCollectionId;
    if (m_localCollectionId < otherlocalCollectionId)
        return true;
    return false;
}

QString QOrganizerCollectionSymbianEngineId::managerUri() const
{
    // TODO: make this return the actual managerUri (including params) of the
    // engine it is associated with
    static const QString managerUri(QLatin1String("qtorganizer:symbian:"));
    return managerUri;
}

QOrganizerCollectionEngineId* QOrganizerCollectionSymbianEngineId::clone() const
{
    QOrganizerCollectionSymbianEngineId *myClone = new QOrganizerCollectionSymbianEngineId;
    myClone->m_localCollectionId = m_localCollectionId;
    return myClone;
}

QString QOrganizerCollectionSymbianEngineId::toString() const
{
    return QString::number(m_localCollectionId);
}

#ifndef QT_NO_DEBUG_STREAM
QDebug& QOrganizerCollectionSymbianEngineId::debugStreamOut(QDebug& dbg) const
{
    dbg.nospace() << "QOrganizerCollectionSymbianEngineId(" << m_localCollectionId << ")";
    return dbg.maybeSpace();
}
#endif

uint QOrganizerCollectionSymbianEngineId::hash() const
{
    return QT_PREPEND_NAMESPACE(qHash)(m_localCollectionId);
}


// Special (internal) error code to be used when an item occurrence is not
// valid. The error code is not expected to clash with any symbian calendar
// API errors.
const TInt KErrInvalidOccurrence(-32768);
const TInt KErrInvalidItemType(-32769);

QOrganizerManagerEngine* QOrganizerItemSymbianFactory::engine(
    const QMap<QString, QString>& parameters, 
    QOrganizerManager::Error* error)
{
    Q_UNUSED(parameters);

    // manager takes ownership and will clean up.
    QOrganizerItemSymbianEngine* ret = new QOrganizerItemSymbianEngine();
    TRAPD(err, ret->initializeL());
    QOrganizerItemSymbianEngine::transformError(err, error);
    if (*error != QOrganizerManager::NoError) {
        // Something went wrong. Return null so that 
        // QOrganizerManagerData::createEngine() will return 
        // QOrganizerItemInvalidEngine to the client. This will avoid null 
        // pointer exceptions if the client still tries to access the manager.
        delete ret;
        ret = 0;
    }
    
    return ret;
}

QOrganizerItemEngineId* QOrganizerItemSymbianFactory::createItemEngineId(const QMap<QString, QString>& parameters, const QString& engineIdString) const
{
    Q_UNUSED(parameters);
    QStringList parts(engineIdString.split(QLatin1String(":")));
    if (parts.size() != 2)
        return NULL;

    bool ok = true;
    quint64 collectionid = parts[0].toULongLong(&ok);
    if (!ok)
        return NULL;
    quint32 itemId = parts[1].toUInt(&ok);
    if (!ok)
        return NULL;
    return new QOrganizerItemSymbianEngineId(collectionid, itemId);
}

QOrganizerCollectionEngineId* QOrganizerItemSymbianFactory::createCollectionEngineId(const QMap<QString, QString>& parameters, const QString& engineIdString) const
{
    Q_UNUSED(parameters);
    bool ok = true;
    quint64 collectionid = engineIdString.toULongLong(&ok);
    if (!ok)
        return NULL;
    else
        return new QOrganizerCollectionSymbianEngineId(collectionid);
}

QString QOrganizerItemSymbianFactory::managerName() const
{
    return QLatin1String("symbian");
}
Q_EXPORT_PLUGIN2(qtorganizer_symbian, QOrganizerItemSymbianFactory);

QOrganizerItemSymbianEngine::QOrganizerItemSymbianEngine() :
    QOrganizerManagerEngine(),
    m_defaultCollection(this),
    m_requestServiceProviderQueue(0)
{

}

void QOrganizerItemSymbianEngine::initializeL()
{
    // Open the default collection
    m_defaultCollection.openL(KNullDesC);
    m_collections.insert(m_defaultCollection.id(), m_defaultCollection);
    m_defaultCollection.createViewsL();

#ifdef SYMBIAN_CALENDAR_V2
    // Start listening to calendar file changes
    m_defaultCollection.calSession()->StartFileChangeNotificationL(*this);
    
    // Load available calendars
    CCalCalendarIterator *iterator = CCalCalendarIterator::NewL(*m_defaultCollection.calSession());
    CleanupStack::PushL(iterator);
    for (CCalCalendarInfo *calInfo=iterator->FirstL(); calInfo != 0; calInfo=iterator->NextL()) {
        
        CleanupStack::PushL(calInfo);

        // Skip calendars which are marked for deletion
        TBool markAsDelete = EFalse;
        TRAP_IGNORE(markAsDelete = getCalInfoPropertyL<TBool>(*calInfo, EMarkAsDelete));
        if (markAsDelete) {
            CleanupStack::PopAndDestroy(calInfo);
            continue;
        }

        // Skip default calendar (already loaded)
        QString fileName = toQString(calInfo->FileNameL());
        if (fileName.compare(m_defaultCollection.fileName(), Qt::CaseInsensitive) == 0) {
            CleanupStack::PopAndDestroy(calInfo);
            continue;
        }
        
        // Open a new session to the calendar
        OrganizerSymbianCollection collection(this);
        collection.openL(calInfo->FileNameL());
        m_collections.insert(collection.id(), collection);
        collection.createViewsL();

        CleanupStack::PopAndDestroy(calInfo);
    }
    CleanupStack::PopAndDestroy(iterator);
#endif
    // Create request queue for asynch requests
    m_requestServiceProviderQueue = QOrganizerItemRequestQueue::instance(*this);
}

QOrganizerItemSymbianEngine::~QOrganizerItemSymbianEngine()
{
	delete m_requestServiceProviderQueue;
}

QString QOrganizerItemSymbianEngine::managerName() const
{
    return QLatin1String("symbian");
}

QMap<QString, QString> QOrganizerItemSymbianEngine::managerParameters() const
{
    /* TODO - in case you have any actual parameters that are relevant that you saved in the factory method, return them here */
    return QMap<QString, QString>();
}

int QOrganizerItemSymbianEngine::managerVersion() const
{
    // This is strictly defined by the engine, so we can return whatever we like
    return 1;
}

QList<QOrganizerItem> QOrganizerItemSymbianEngine::itemOccurrences(
    const QOrganizerItem& parentItem,
    const QDateTime& periodStart,
    const QDateTime& periodEnd,
    int maxCount,
    const QOrganizerItemFetchHint& fetchHint,
    QOrganizerManager::Error* error) const
{
    QList<QOrganizerItem> itemOccurrences;
    TRAPD(err, itemOccurrences = itemOccurrencesL(parentItem.id(), periodStart, periodEnd, maxCount, fetchHint));
    transformError(err, error);
    return itemOccurrences;
}

QList<QOrganizerItem> QOrganizerItemSymbianEngine::itemOccurrencesL(
    const QOrganizerItemId &parentItemId,
    const QDateTime &periodStart,
    const QDateTime &periodEnd,
    int maxCount,
    const QOrganizerItemFetchHint& fetchHint) const
{
    Q_UNUSED(fetchHint)

    //Verify maximum number of items requested
    if (0 == maxCount)
    {
        //Return an empty occurrence list if maxCount is 0
        return QList<QOrganizerItem>();
    }

    // Verify that parent item exists
    QOrganizerManager::Error error;
    QOrganizerItem parentItem = this->item(parentItemId, QOrganizerItemFetchHint(), &error);
    if (error != QOrganizerManager::NoError)
        return QList<QOrganizerItem>(); // return an empty occurrence list if parent item is not found

    // Verify time range
    if (periodStart.isValid() && periodEnd.isValid() && periodEnd < periodStart)
        User::Leave(KErrArgument);

    // Set cal view filter based on the item type
    CalCommon::TCalViewFilter filter(0);
    if (parentItem.type() == QOrganizerItemType::TypeEvent) {
        filter = CalCommon::EIncludeAppts | CalCommon::EIncludeEvents;
    } else if (parentItem.type() == QOrganizerItemType::TypeTodo) {
        filter = (CalCommon::EIncludeCompletedTodos | CalCommon::EIncludeIncompletedTodos);
    } else {
        User::Leave(KErrInvalidItemType);
    }

    // If start time is not defined, use minimum start date
    TCalTime startTime;
    startTime.SetTimeUtcL(TCalTime::MinTime());
    if (periodStart.isValid())
        startTime.SetTimeLocalL(toTTime(periodStart, Qt::LocalTime));

    // If end date is not defined, use maximum end date
    TCalTime endTime;
    endTime.SetTimeUtcL(TCalTime::MaxTime());
    if (periodEnd.isValid())
        endTime.SetTimeLocalL(toTTime(periodEnd, Qt::LocalTime));

    // Find instances
    RPointerArray<CCalInstance> instanceList;
    CleanupResetAndDestroyPushL(instanceList);
    m_collections[parentItem.collectionId()].calInstanceView()->FindInstanceL(
        instanceList, filter, CalCommon::TCalTimeRange(startTime, endTime));
    
    // Transform CCalInstances to QOrganizerItems
    QList<QOrganizerItem> itemOccurrences;
    toItemOccurrencesL(instanceList, parentItem, maxCount, parentItem.collectionId(), itemOccurrences);
    
    CleanupStack::PopAndDestroy(&instanceList);
    
    return itemOccurrences;
}

QList<QOrganizerItem> QOrganizerItemSymbianEngine::items(
    const QDateTime& periodStart,
    const QDateTime& periodEnd,
    const QOrganizerItemFilter& filter,
    const QList<QOrganizerItemSortOrder>& sortOrders,
    const QOrganizerItemFetchHint& fetchHint,
    QOrganizerManager::Error* error) const
{
    QList<QOrganizerItem> items;
    TRAPD(err, items = itemOccurrencesL(periodStart, periodEnd, filter, sortOrders, fetchHint));
    transformError(err, error);
    return items;
}

QList<QOrganizerItem> QOrganizerItemSymbianEngine::itemOccurrencesL(
    const QDateTime& periodStart,
    const QDateTime& periodEnd,
    const QOrganizerItemFilter &filter,
    const QList<QOrganizerItemSortOrder> &sortOrders,
    const QOrganizerItemFetchHint &fetchHint) const
{
    // TODO: It might be possible to optimize by using fetch hint
    Q_UNUSED(fetchHint);
    
    // Verify time range
    if (periodStart.isValid() && periodEnd.isValid() && periodEnd < periodStart)
        User::Leave(KErrArgument);  

    // If start time is not defined, use minimum start date
    TCalTime startTime;
    startTime.SetTimeUtcL(TCalTime::MinTime());
    if (periodStart.isValid())
        startTime.SetTimeLocalL(toTTime(periodStart, Qt::LocalTime));

    // If end date is not defined, use maximum end date
    TCalTime endTime;
    endTime.SetTimeUtcL(TCalTime::MaxTime());
    if (periodEnd.isValid())
        endTime.SetTimeLocalL(toTTime(periodEnd, Qt::LocalTime));

    // Loop through all the instance views and fetch the item instances
    QList<QOrganizerItem> items;
    QList<OrganizerSymbianCollection> collections = filteredSymbianCollectionsL(filter);
    foreach (OrganizerSymbianCollection collection, collections) {
        
        // Get instances
        RPointerArray<CCalInstance> instanceList;
        CleanupResetAndDestroyPushL(instanceList);
        collection.calInstanceView()->FindInstanceL(
            instanceList, CalCommon::EIncludeAll, CalCommon::TCalTimeRange(startTime, endTime));
        
        // Transform CCalInstances to QOrganizerItems
        toItemOccurrencesL(instanceList, QOrganizerItem(), -1, collection.id(), items);
        
        CleanupStack::PopAndDestroy(&instanceList);
    }

    // Use the general implementation to filter and sort items
    return slowFilterItems(items, filter, sortOrders);
}

void QOrganizerItemSymbianEngine::toItemOccurrencesL(
    const RPointerArray<CCalInstance> &calInstanceList,
    QOrganizerItem parentItem,
    const int maxCount,
    QOrganizerCollectionId collectionId,
    QList<QOrganizerItem> &itemOccurrences) const
{
    quint64 localCollectionIdValue = m_collections[collectionId].calCollectionId();

    // Counter for the found match items
    int count = 0;
    // Transform all the instances to QOrganizerItems
    for(int i(0); i < calInstanceList.Count(); i++) {
        QOrganizerItem itemOccurrence;
        CCalInstance* calInstance = calInstanceList[i];
        m_itemTransform.toItemOccurrenceL(*calInstance, &itemOccurrence);

        // Optimization: if a parent item instance is defined, skip the instances that do not match
        if (!parentItem.isEmpty() && parentItem.guid() != itemOccurrence.guid())
            continue;

        // Found one match item
        count++;
        // Check if maxCount limit is reached
        if (maxCount > 0 && count > maxCount)
            break;

        // Set local id if this is either an exceptional item or a non-recurring item
        CCalEntry &entry = calInstance->Entry();
        bool isException = entry.RecurrenceIdL().TimeUtcL() != Time::NullTTime();
        TCalRRule rrule;
        bool isRecurring = entry.GetRRuleL(rrule);
        if (isException || !isRecurring) {
            QOrganizerItemId itemId = QOrganizerItemId(new QOrganizerItemSymbianEngineId(
                localCollectionIdValue, calInstance->Entry().LocalUidL()));
            itemOccurrence.setId(itemId);
        }

        // Set instance origin, the detail is set here because transform classes are not aware of
        // the required APIs
        if (isException || isRecurring) {
            TCalLocalUid parentLocalUid(0);
            if (isException) {
                HBufC8* globalUid = OrganizerItemGuidTransform::guidLC(itemOccurrence);
                CCalEntry *parentEntry = findParentEntryLC(collectionId, itemOccurrence, *globalUid);
                parentLocalUid = parentEntry->LocalUidL();
                CleanupStack::PopAndDestroy(parentEntry);
                CleanupStack::PopAndDestroy(globalUid);
            } else {
                parentLocalUid = calInstance->Entry().LocalUidL();
            }
            QOrganizerItemParent origin(itemOccurrence.detail<QOrganizerItemParent>());
            origin.setParentId(toItemId(localCollectionIdValue, parentLocalUid));
            origin.setOriginalDate(toQDateTimeL(calInstance->StartTimeL()).date());
            itemOccurrence.saveDetail(&origin);
        }

        // Set collection id
        itemOccurrence.setCollectionId(collectionId);

        itemOccurrences.append(itemOccurrence);
    }
}

QList<QOrganizerItemId> QOrganizerItemSymbianEngine::itemIds(
        const QDateTime& periodStart,
        const QDateTime& periodEnd,
        const QOrganizerItemFilter& filter,
        const QList<QOrganizerItemSortOrder>& sortOrders,
        QOrganizerManager::Error* error) const
{
    QList<QOrganizerItemId> ids;
    TRAPD(err, ids = itemIdsL(periodStart, periodEnd, filter, sortOrders))
    transformError(err, error);
    return ids;
}

QList<QOrganizerItemId> QOrganizerItemSymbianEngine::itemIdsL(
    const QDateTime& periodStart,
    const QDateTime& periodEnd,
    const QOrganizerItemFilter& filter, 
    const QList<QOrganizerItemSortOrder>& sortOrders) const
{
    QList<OrganizerSymbianCollection> collections = filteredSymbianCollectionsL(filter);   
    QList<QOrganizerItemId> itemIds = itemIdsL(collections, periodStart, periodEnd);
    return slowFilterIdsL(itemIds, filter, sortOrders);
}

QList<QOrganizerItemId> QOrganizerItemSymbianEngine::itemIdsL(
    const QList<OrganizerSymbianCollection> &collections,
    const QDateTime& periodStart,
    const QDateTime& periodEnd) const
{
    // Verify time range
    if (periodStart.isValid() && periodEnd.isValid() && periodEnd < periodStart)
        User::Leave(KErrArgument);
    
    QSet<QOrganizerItemId> itemIds;
    foreach (OrganizerSymbianCollection collection, collections) {

        if (!periodStart.isValid() && !periodEnd.isValid()) {

            // Time range is not defined. So we can just return all entries. 
            // NOTE: this a lot faster than using instance view

            // Get all entries
            TCalTime minTime;
            minTime.SetTimeUtcL(TCalTime::MinTime());
            RArray<TCalLocalUid> ids;
            CleanupClosePushL(ids);
            collection.calEntryView()->GetIdsModifiedSinceDateL(minTime, ids);

            // Convert to item id's
            int count = ids.Count();
            for (int i=0; i<count; i++)
                itemIds << toItemId(collection.calCollectionId(), ids[i]);

            CleanupStack::PopAndDestroy(&ids);

        } else {

            // Time range is defined so we need to use instance view to find
            // all entries in the range. For example an item which starts before
            // periodStart might have an occurrence in the range. We cannot catch 
            // that through CCalEntryView.
            // NOTE: If the client does not define periodEnd we might get
            // a huge amount of instances!

            // If start time is not defined, use minimum start date
            TCalTime startTime;
            startTime.SetTimeUtcL(TCalTime::MinTime());
            if (periodStart.isValid())
                startTime.SetTimeLocalL(toTTime(periodStart, Qt::LocalTime));

            // If end date is not defined, use maximum end date
            TCalTime endTime;
            endTime.SetTimeUtcL(TCalTime::MaxTime());
            if (periodEnd.isValid())
                endTime.SetTimeLocalL(toTTime(periodEnd, Qt::LocalTime));

            // Find instances
            RPointerArray<CCalInstance> instances;
            CleanupResetAndDestroyPushL(instances);
            collection.calInstanceView()->FindInstanceL(
                instances, CalCommon::EIncludeAll, CalCommon::TCalTimeRange(startTime, endTime));

            // Get parent entry ids from instances
            for (int i=0; i<instances.Count(); i++) {
                QOrganizerItemId id = toItemId(collection.calCollectionId(), instances[i]->Entry().LocalUidL());
                if (!itemIds.contains(id))
                    itemIds << id;
            }

            CleanupStack::PopAndDestroy(&instances);
        }
    }
    return itemIds.toList();
}
QList<QOrganizerItem> QOrganizerItemSymbianEngine::itemsForExport(
    const QDateTime& periodStart,
    const QDateTime& periodEnd,
    const QOrganizerItemFilter& filter, 
    const QList<QOrganizerItemSortOrder>& sortOrders, 
    const QOrganizerItemFetchHint& fetchHint, 
    QOrganizerManager::Error* error) const
{
    Q_UNUSED(fetchHint);
    QList<QOrganizerItem> itemsList;
    TRAPD(err, itemsList = itemsForExportL(periodStart, periodEnd, filter, sortOrders));
    transformError(err, error);
    return itemsList;
}

QList<QOrganizerItem> QOrganizerItemSymbianEngine::itemsForExportL( 
    const QDateTime& periodStart,
    const QDateTime& periodEnd,
    const QOrganizerItemFilter& filter, 
    const QList<QOrganizerItemSortOrder>& sortOrders) const
{
    QList<OrganizerSymbianCollection> collections = filteredSymbianCollectionsL(filter);   
    QList<QOrganizerItemId> itemIds = itemIdsL(collections, periodStart, periodEnd);
    return slowFilterIdsToItemsL(itemIds, filter, sortOrders);
}

QOrganizerItem QOrganizerItemSymbianEngine::item(
    const QOrganizerItemId& itemId, 
    const QOrganizerItemFetchHint& fetchHint, 
    QOrganizerManager::Error* error) const
{
    QOrganizerItem item;
    TRAPD(err, item = itemL(itemId, fetchHint));
    transformError(err, error);
    return item;
}

QOrganizerItem QOrganizerItemSymbianEngine::itemL(const QOrganizerItemId& itemId, 
    const QOrganizerItemFetchHint& fetchHint) const
{
	Q_UNUSED(fetchHint)

    if (itemId.managerUri() != managerUri()) // XXX TODO: cache managerUri for fast lookup.
        User::Leave(KErrNotFound);

    // Check collection id
    QOrganizerCollectionId collectionLocalId = getCollectionId(itemId);
    if (!m_collections.contains(collectionLocalId))
        User::Leave(KErrNotFound);
    
    // Get entry from collection
    TCalLocalUid calLocalId = toTCalLocalUid(itemId);
    CCalEntry *calEntry = m_collections[collectionLocalId].calEntryView()->FetchL(calLocalId);
    if (!calEntry)
        User::Leave(KErrNotFound);
    CleanupStack::PushL(calEntry);

    // Transform CCalEntry -> QOrganizerItem
    QOrganizerItem item;
    m_itemTransform.toItemL(*calEntry, &item);
    
    // Set instance origin
    if (item.type() == QOrganizerItemType::TypeEventOccurrence
        || item.type() == QOrganizerItemType::TypeTodoOccurrence) {
        HBufC8* globalUid = OrganizerItemGuidTransform::guidLC(item);
        quint64 localCollectionIdValue = m_collections[collectionLocalId].calCollectionId();
        CCalEntry *parentEntry = findParentEntryLC(collectionLocalId, item, *globalUid);

        // Set instance origin, the detail is set here because the corresponding transform class
        // does not know the required values
        QOrganizerItemParent origin(item.detail<QOrganizerItemParent>());
        origin.setParentId(toItemId(localCollectionIdValue, parentEntry->LocalUidL()));
        origin.setOriginalDate(toQDateTimeL(calEntry->StartTimeL()).date());
        item.saveDetail(&origin);

        CleanupStack::PopAndDestroy(parentEntry);
        CleanupStack::PopAndDestroy(globalUid);
    }
    CleanupStack::PopAndDestroy(calEntry);
    
    // Set item id
    item.setId(itemId);

    // Set collection id
    item.setCollectionId(collectionLocalId);
    
    return item;
}

bool QOrganizerItemSymbianEngine::saveItems(QList<QOrganizerItem> *items, 
    QMap<int, QOrganizerManager::Error> *errorMap, 
    QOrganizerManager::Error* error)
{
    // TODO: the performance would be probably better, if we had a separate
    // implementation for the case with a list of items that would save all
    // the items
    
    QOrganizerItemChangeSet changeSet;
    
    for (int i(0); i < items->count(); i++) {
        QOrganizerItem item = items->at(i);
        
        // Validate & save
        QOrganizerManager::Error saveError;
        if (validateItem(item, &saveError)) {
            TRAPD(err, saveItemL(&item, &changeSet));
            transformError(err, &saveError);
        }
        
        // Check error
        if (saveError != QOrganizerManager::NoError) {
            *error = saveError;
            if (errorMap)
                errorMap->insert(i, *error);
        } else {
            // Update the item with the data that is available after save
            items->replace(i, item);
        }
    }
    
    // Emit changes
    changeSet.emitSignals(this);
    
    return *error == QOrganizerManager::NoError;
}

bool QOrganizerItemSymbianEngine::saveItem(QOrganizerItem* item, 
    QOrganizerManager::Error* error)
{
    // Validate & save
    if (validateItem(*item, error)) {
        QOrganizerItemChangeSet changeSet;
        TRAPD(err, saveItemL(item, &changeSet));
        transformError(err, error);
        changeSet.emitSignals(this);
    }
    return *error == QOrganizerManager::NoError;
}

void QOrganizerItemSymbianEngine::saveItemL(QOrganizerItem *item, 
    QOrganizerItemChangeSet *changeSet)
{
    QOrganizerCollectionId completeCollectionId;
    QOrganizerCollectionId collectionId;
    if (item) {
        completeCollectionId = item->collectionId();
        collectionId = item->collectionId();
    }
    QOrganizerCollectionId collectionLocalId = collectionIdL(*item,
        collectionId);

    // Find the entry corresponding to the item or to the item occurrence.
    // Creates a new one, if the corresponding entry does not exist yet.
    CCalEntry *entry(0);
    bool isNewEntry(false);
    if(item->type()== QOrganizerItemType::TypeEventOccurrence
        || item->type()== QOrganizerItemType::TypeTodoOccurrence) {
        entry = entryForItemOccurrenceL(collectionLocalId, *item, isNewEntry);
    } else {
        entry = entryForItemL(collectionLocalId, *item, isNewEntry);
    }
    CleanupStack::PushL(entry);

    // Transform QOrganizerItem -> CCalEntry    
    m_itemTransform.toEntryL(*item, entry);

    // Save entry to the database
    RPointerArray<CCalEntry> entries;
    CleanupClosePushL(entries);
    entries.AppendL(entry);
    TInt count(0);
    entryViewL(collectionLocalId)->StoreL(entries, count);
    if (count != entries.Count()) {
        // The documentation states about count "On return, this
        // contains the number of entries which were successfully stored".
        // So it is not clear which error caused storing the entry to fail
        // -> let's use the "one-error-fits-all" error code KErrGeneral.
        User::Leave(KErrGeneral);
    }

    // Transform details that are available/updated after saving    
    m_itemTransform.toItemPostSaveL(*entry, item, managerUri());
    
    // Update id
    item->setId(toItemId(m_collections[collectionLocalId].calCollectionId(), entry->LocalUidL()));

    // Set collection id
    item->setCollectionId(collectionLocalId);

    // Cleanup
    CleanupStack::PopAndDestroy(&entries);
    CleanupStack::PopAndDestroy(entry);

    // Update change set for signal emissions
    if (changeSet) {
        if (isNewEntry)
            changeSet->insertAddedItem(item->id());
        else
            changeSet->insertChangedItem(item->id());
    }
}

/*!
 * Retrieves the entry view for the collection. Leaves with KErrArgument if
 * not found.
 */
CCalEntryView* QOrganizerItemSymbianEngine::entryViewL(
    const QOrganizerCollectionId& collectionId) const
{
    QOrganizerCollectionId tempCollectionId = collectionId;

    // Null is interpreted as the default collection
    if (tempCollectionId.isNull())
        tempCollectionId = m_defaultCollection.id();

    if (!m_collections.contains(tempCollectionId))
        User::Leave(KErrArgument);

    return m_collections[tempCollectionId].calEntryView();
}

/*!
 * Retrieves the instance view for the collection. Leaves with KErrArgument if
 * not found.
 */
CCalInstanceView* QOrganizerItemSymbianEngine::instanceViewL(const QOrganizerCollectionId& collectionId) const
{
    QOrganizerCollectionId tempCollectionId = collectionId;

    // Null is interpreted as the default collection
    if (tempCollectionId.isNull())
        tempCollectionId = m_defaultCollection.id();

    if (!m_collections.contains(tempCollectionId))
        User::Leave(KErrArgument);

    return m_collections[tempCollectionId].calInstanceView();
}
    
/*!
 * Returns item's collection id if it is valid. If not returns collectionId
 * given as a parameter if it is valid. Fallback is to return the default
 * session's collection id.
 */
QOrganizerCollectionId QOrganizerItemSymbianEngine::collectionIdL(
    const QOrganizerItem &item, const QOrganizerCollectionId &collectionId) const
{
#ifdef SYMBIAN_CALENDAR_V2
    QOrganizerCollectionId itemCollectionId = item.collectionId();

    if (!itemCollectionId.isNull() && !collectionId.isNull()
        && collectionId != itemCollectionId)
            User::Leave(KErrArgument);
    else if (!collectionId.isNull())
        return collectionId;
    else if (!itemCollectionId.isNull())
        return itemCollectionId;
#else
    Q_UNUSED(item);
    Q_UNUSED(collectionId);
#endif
    
    // Default collection id is the default session's collection id
    return m_defaultCollection.id();
}

CCalEntry* QOrganizerItemSymbianEngine::entryForItemOccurrenceL(
    const QOrganizerCollectionId &collectionId, const QOrganizerItem &item, 
    bool &isNewEntry) const
{
    CCalEntry * entry(NULL);

    // Check manager uri (if provided)
    if (!item.id().managerUri().isEmpty()) {
        if (item.id().managerUri() != managerUri())
            User::Leave(KErrInvalidOccurrence);
    }

    // Find the child entry corresponding to the item occurrence
    if (!item.id().isNull()) {
        // Fetch the item (will return NULL if the localid is not found)
        entry = entryViewL(collectionId)->FetchL(toTCalLocalUid(item.id()));
        if (!entry)
            User::Leave(KErrInvalidOccurrence);
        return entry;
    }

    // Entry not found, find the parent entry and create a new child for it
    HBufC8* parentGlobalUid(OrganizerItemGuidTransform::guidLC(item));
    CCalEntry *parentEntry(
        findParentEntryLC(collectionId, item, *parentGlobalUid));

    // Get the parameters for the new child entry
    QOrganizerItemParent origin(
        item.detail<QOrganizerItemParent>());
    if (!origin.originalDate().isValid()) {
        User::Leave(KErrInvalidOccurrence);
    }
    QDateTime parentStartTime = toQDateTimeL(parentEntry->StartTimeL());
    QDateTime recurrenceDateTime = QDateTime(origin.originalDate(), parentStartTime.time());
    TCalTime recurrenceId = toTCalTimeL(recurrenceDateTime);
    HBufC8* globalUid = HBufC8::NewLC(parentEntry->UidL().Length());
    globalUid->Des().Copy(parentEntry->UidL());

    // Create the new child entry
    entry = CCalEntry::NewL(parentEntry->EntryTypeL(),
                            globalUid,
                            parentEntry->MethodL(),
                            parentEntry->SequenceNumberL(),
                            recurrenceId,
                            CalCommon::EThisOnly);
    isNewEntry = true;
    CleanupStack::Pop(globalUid); // Ownership transferred
    CleanupStack::PopAndDestroy(parentEntry);
    CleanupStack::PopAndDestroy(parentGlobalUid);

    return entry; // Ownership transferred
}

CCalEntry* QOrganizerItemSymbianEngine::entryForItemL(
    const QOrganizerCollectionId &collectionId, 
    const QOrganizerItem &item, bool &isNewEntry) const
{
    // Try to find with local id
    CCalEntry *entry = findEntryL(collectionId, item.id(), item.id().managerUri());

    // Not found. Try to find with globalUid
    if (!entry) {
        HBufC8* globalUid = OrganizerItemGuidTransform::guidLC(item);

        entry = findEntryL(collectionId, *globalUid);
        // Not found? Create a new entry instance to be saved to the database
        if (!entry) {
            CCalEntry::TType type = OrganizerItemTypeTransform::entryTypeL(item);
            entry = CCalEntry::NewL(type, globalUid, CCalEntry::EMethodAdd, 0);
            isNewEntry = true;
            CleanupStack::Pop(globalUid); // Ownership transferred to the new entry
            return entry;
        }
        CleanupStack::PopAndDestroy(globalUid);
    }
    return entry;
}

CCalEntry * QOrganizerItemSymbianEngine::findEntryL(
    const QOrganizerCollectionId &collectionId, 
    const QOrganizerItemId &id, QString manageruri) const
{
    CCalEntry *entry(0);

    // Check that manager uri match to this manager (if provided)
    if (!manageruri.isEmpty()) {
        if (manageruri != managerUri())
            User::Leave(KErrArgument);
    }

    // There must be an existing entry if id is provided
    if (!id.isNull()) {
        // Fetch the item (will return NULL if the id is not found)
        entry = entryViewL(collectionId)->FetchL(toTCalLocalUid(id));
        if (!entry)
            User::Leave(KErrNotFound);
    }

    // ownership transferred
    return entry;
}

CCalEntry * QOrganizerItemSymbianEngine::findEntryL(
    const QOrganizerCollectionId &collectionId, 
    const TDesC8& globalUid) const
{
    CCalEntry *entry(0);

    if (globalUid.Length()) {
        // Search for an existing entry based on guid
        RPointerArray<CCalEntry> calEntryArray;
        CleanupResetAndDestroyPushL(calEntryArray);
        entryViewL(collectionId)->FetchL(globalUid, calEntryArray);
        if (calEntryArray.Count()) {
            // take the first item in the array
            entry = calEntryArray[0];
            calEntryArray.Remove(0);
        }
        CleanupStack::PopAndDestroy(&calEntryArray);
    }

    // ownership transferred
    return entry;
}

CCalEntry* QOrganizerItemSymbianEngine::findParentEntryLC(
    const QOrganizerCollectionId &collectionId, 
    const QOrganizerItem &item, const TDesC8& globalUid) const
{
    CCalEntry *parent(0);

    // Try to find with parent's id
    QOrganizerItemParent origin = item.detail<QOrganizerItemParent>();
    if (!origin.parentId().isNull()) {
        // Fetch the item (will return NULL if the id is not found)
        parent = entryViewL(collectionId)->FetchL(toTCalLocalUid(origin.parentId())); // ownership transferred
        if (!parent)
            User::Leave(KErrInvalidOccurrence);
        CleanupStack::PushL(parent);
    // Try to find with globalUid
    } else if (globalUid.Length()) {
        parent = findEntryL(collectionId, globalUid);
        if (!parent)
            User::Leave(KErrInvalidOccurrence);
        CleanupStack::PushL(parent);

    } else {
        User::Leave(KErrInvalidOccurrence);
    }

    // Verify the item against parent
    if(parent->EntryTypeL() != OrganizerItemTypeTransform::entryTypeL(item))
        User::Leave(KErrInvalidOccurrence);

    // Check for UID consistency for item with parentEntry
    if (!item.guid().isEmpty()
        && globalUid.Compare(parent->UidL())) {
        // Guid is not consistent with parentEntry UID
        User::Leave(KErrInvalidOccurrence);
    } else if (!origin.parentId().isNull()
        && (toTCalLocalUid(origin.parentId()) != parent->LocalUidL())) {
        // parentId is not consistent with parentEntry localUID
        User::Leave(KErrInvalidOccurrence);
    }

    return parent;
}

bool QOrganizerItemSymbianEngine::removeItems(
    const QList<QOrganizerItemId>& itemIds, 
    QMap<int, QOrganizerManager::Error>* errorMap, 
    QOrganizerManager::Error* error)
{
    // Note: the performance would be probably better, if we had a separate
    // implementation for the case with a list of item ids that would
    // remove all the items

    QOrganizerItemChangeSet changeSet;

    for (int i(0); i < itemIds.count(); i++) {
        // Remove
        QOrganizerManager::Error removeError(
            QOrganizerManager::NoError);
        TRAPD(err, removeItemL(itemIds.at(i)));
        if (err != KErrNone) {
            transformError(err, &removeError);
            *error = removeError;
            if (errorMap)
                errorMap->insert(i, *error);
        } else {
            // Signals
            changeSet.insertRemovedItem(itemIds.at(i));
        }
    }

    // Emit changes
    changeSet.emitSignals(this);

    return *error == QOrganizerManager::NoError;
}

bool QOrganizerItemSymbianEngine::removeItem(
    const QOrganizerItemId& organizeritemId, 
    QOrganizerManager::Error* error)
{
    TRAPD(err, removeItemL(organizeritemId));
    if (err != KErrNone) {
        transformError(err, error);
    } else {
        // Signals
        QOrganizerItemChangeSet changeSet;
        changeSet.insertRemovedItem(organizeritemId);
        changeSet.emitSignals(this);
    }
    return *error == QOrganizerManager::NoError;
}

void QOrganizerItemSymbianEngine::removeItemL(
    const QOrganizerItemId& organizeritemId)
{
    // TODO: How to remove item instances?

    if (organizeritemId.managerUri() != managerUri()) // XXX TODO: cache managerUri for fast lookup.
        User::Leave(KErrNotFound);

    QOrganizerCollectionId collectionId = getCollectionId(organizeritemId);
    if (!m_collections.contains(collectionId))
        User::Leave(KErrNotFound);

    // Find entry
    TCalLocalUid calLocalId = toTCalLocalUid(organizeritemId);
    CCalEntry *calEntry = entryViewL(collectionId)->FetchL(calLocalId);
    CleanupStack::PushL(calEntry);
    if (!calEntry)
        User::Leave(KErrNotFound);

    // Remove entry
    entryViewL(collectionId)->DeleteL(*calEntry);
    CleanupStack::PopAndDestroy(calEntry);
}

QList<QOrganizerItem> QOrganizerItemSymbianEngine::slowFilterIdsToItemsL(
    const QList<QOrganizerItemId> &itemIds,
    const QOrganizerItemFilter& filter, 
    const QList<QOrganizerItemSortOrder>& sortOrders) const
{
    // Nothing to filter?
    if (filter.type() == QOrganizerItemFilter::InvalidFilter)
        return QList<QOrganizerItem>();
    
    // Get item. Filter and sort it.
    QList<QOrganizerItem> filteredAndSorted;
    foreach (const QOrganizerItemId &id, itemIds)
        addFilteredAndSorted(&filteredAndSorted, itemL(id, QOrganizerItemFetchHint()), filter, sortOrders);

    return filteredAndSorted;
}

QList<QOrganizerItemId> QOrganizerItemSymbianEngine::slowFilterIdsL(
    const QList<QOrganizerItemId> &itemIds,
    const QOrganizerItemFilter& filter, 
    const QList<QOrganizerItemSortOrder>& sortOrders) const
{
    // Nothing to filter?
    if (filter.type() == QOrganizerItemFilter::InvalidFilter)
        return QList<QOrganizerItemId>();
    
    // No filtering and sorting needed?
    if (filter.type() == QOrganizerItemFilter::DefaultFilter && sortOrders.count() == 0)
        return itemIds;    
    
    // Get item. Filter and sort it.
    QList<QOrganizerItem> filteredAndSorted;
    foreach (const QOrganizerItemId &id, itemIds)
        addFilteredAndSorted(&filteredAndSorted, itemL(id, QOrganizerItemFetchHint()), filter, sortOrders);

    // Convert items to item id's
    QList<QOrganizerItemId> ids;
    foreach (const QOrganizerItem& item, filteredAndSorted)
        ids << item.id();
        
    return ids;
}

QList<QOrganizerItem> QOrganizerItemSymbianEngine::slowFilterItems(
    const QList<QOrganizerItem> &items,
    const QOrganizerItemFilter& filter, 
    const QList<QOrganizerItemSortOrder>& sortOrders) const
{
    // Nothing to filter?
    if (filter.type() == QOrganizerItemFilter::InvalidFilter)
        return QList<QOrganizerItem>();
    
    // No filtering and sorting needed?
    if (filter.type() == QOrganizerItemFilter::DefaultFilter && sortOrders.count() == 0)
        return items; 
    
    // Filter and sort
    QList<QOrganizerItem> filteredAndSorted;
    foreach(const QOrganizerItem& item, items)
        addFilteredAndSorted(&filteredAndSorted, item, filter, sortOrders);
    return filteredAndSorted;
}

void QOrganizerItemSymbianEngine::addFilteredAndSorted(
    QList<QOrganizerItem> *items,
    const QOrganizerItem &item,
    const QOrganizerItemFilter& filter,
    const QList<QOrganizerItemSortOrder>& sortOrders) const
{
    if (filter.type() == QOrganizerItemFilter::DefaultFilter) {
        QOrganizerManagerEngine::addSorted(items, item, sortOrders); // only sorting needed
    } else {
        if (QOrganizerManagerEngine::testFilter(filter, item))
            QOrganizerManagerEngine::addSorted(items, item, sortOrders);
    }
}

QList<OrganizerSymbianCollection> QOrganizerItemSymbianEngine::filteredSymbianCollectionsL(
    const QOrganizerItemFilter &filter) const
{
    // No filter for collections?
    if (filter.type() == QOrganizerItemFilter::DefaultFilter)
        return m_collections.values();
    
    // Nothing to filter?
    if (filter.type() == QOrganizerItemFilter::InvalidFilter)
        return QList<OrganizerSymbianCollection>();
    
    // Get filters
    QList<QOrganizerItemFilter> filters;
    if (filter.type() == QOrganizerItemFilter::UnionFilter) 
        filters = static_cast<QOrganizerItemUnionFilter>(filter).filters();
    if (filter.type() == QOrganizerItemFilter::CollectionFilter)
        filters.append(filter);
    
    // TODO: QOrganizerItemFilter::IntersectionFilter
    // Implementing this is not really worth the effort. It's an unlikely use case.
    // Simpler just to return all collections and let slowfilter handle this.
    
    // Get collection ids from collection filters
    QList<QOrganizerCollectionId> cIds;
    foreach (const QOrganizerItemFilter &f, filters) {
        if (f.type() == QOrganizerItemFilter::CollectionFilter)
            cIds << static_cast<QOrganizerItemCollectionFilter>(f).collectionIds().toList();
    }
    
    // No filter found?
    if (cIds.count() == 0)
        return m_collections.values();
    
    // Find matching collections
    QList<OrganizerSymbianCollection> collections;
    foreach (const QOrganizerCollectionId &id, cIds) {
        if (m_collections.contains(id))
            collections << m_collections[id];
        else
            User::Leave(KErrArgument); // TODO: Not really sure if we should leave in this case...
    }    
    return collections;
}

QOrganizerCollection QOrganizerItemSymbianEngine::defaultCollection(
    QOrganizerManager::Error* error) const
{
    *error = QOrganizerManager::NoError;
    return m_defaultCollection.toQOrganizerCollectionL();
}

QOrganizerCollection QOrganizerItemSymbianEngine::collection(
    const QOrganizerCollectionId& collectionId,
    QOrganizerManager::Error* error) const
{
    if (m_collections.contains(collectionId))
        return (m_collections[collectionId].toQOrganizerCollectionL());
    *error = QOrganizerManager::DoesNotExistError;
    return QOrganizerCollection();
}

QList<QOrganizerCollection> QOrganizerItemSymbianEngine::collections(
    QOrganizerManager::Error* error) const
{
    // Get collections
    QList<QOrganizerCollection> collections;
    TRAPD(err, collections = collectionsL());
    transformError(err, error);
    return collections;
}

QList<QOrganizerCollection> QOrganizerItemSymbianEngine::collectionsL() const
{
    QList<QOrganizerCollection> collections;
    QList<QOrganizerCollectionId> collectionIds = m_collections.keys();
    foreach (const QOrganizerCollectionId &id, collectionIds) {
        collections << m_collections[id].toQOrganizerCollectionL();
    }
    return collections;
}

bool QOrganizerItemSymbianEngine::saveCollection(
    QOrganizerCollection* collection, 
    QOrganizerManager::Error* error)
{
    bool isNewCollection = true;
    if (!collection->id().isNull())
        isNewCollection = false;
    
    TRAPD(err, saveCollectionL(collection));
    transformError(err, error);

    if (*error == QOrganizerManager::NoError) {
        if (isNewCollection) {
            // Emit changes
            QOrganizerCollectionChangeSet changeSet;
            changeSet.insertAddedCollection(collection->id());
            changeSet.emitSignals(this);
        }
        // NOTE: collectionsChanged signal will be emitted from 
        // CalendarInfoChangeNotificationL
    }

    return (*error == QOrganizerManager::NoError);   
}

void QOrganizerItemSymbianEngine::saveCollectionL(
    QOrganizerCollection* collection)
{
#ifndef SYMBIAN_CALENDAR_V2
    Q_UNUSED(collection);
    User::Leave(KErrNotSupported);
#else
    // Check manager uri if defined
    if (!collection->id().managerUri().isEmpty()) {
        if (collection->id().managerUri() != this->managerUri())
            User::Leave(KErrArgument); // uri does not match this manager
    }
    
    // Find existing collection
    QOrganizerCollectionId id = collection->id();
    OrganizerSymbianCollection symbianCollection(this);
    if (!id.isNull()) {
        if (m_collections.contains(id))
            symbianCollection = m_collections[id];
        else
            User::Leave(KErrArgument); // collection id was defined but was not found 
    }

    // Convert into a compatible collection
    QOrganizerManager::Error error(QOrganizerManager::NoError);
    *collection = compatibleCollection(*collection, &error);
    if (error != QOrganizerManager::NoError)
        User::Leave(KErrArgument); // Could not convert -> collection not valid

    // Convert metadata to cal info
    CCalCalendarInfo *calInfo = toCalInfoLC(collection->metaData());
    
    // Update modification time
    TTime currentTime;
    currentTime.UniversalTime();
    setCalInfoPropertyL(calInfo, EModificationTime, currentTime);
    
    // Get filename from collection to be saved
    QString fileName = collection->metaData(OrganizerSymbianCollection::KeyFileName).toString();
    
    // Did we found an existing collection?
    if (!symbianCollection.isValid()) {

        // Set creation time
        setCalInfoPropertyL(calInfo, ECreationTime, currentTime);
        
        // If filename is not provided use collection name as a filename
        if (fileName.isEmpty())
            fileName = collection->metaData(QOrganizerCollection::KeyName).toString();
                
        // Create a new collection
        symbianCollection.openL(toPtrC16(fileName), calInfo);
        m_collections.insert(symbianCollection.id(), symbianCollection);
        symbianCollection.createViewsL();
    }
    else {
        // Cannot allow changing the filename for an existing collection
        if (symbianCollection.fileName() != fileName)
            User::Leave(KErrArgument);

        // Preserve creation time by copying it from the old cal info
        TTime creationTime = Time::NullTTime();
        CCalCalendarInfo *calInfoOld = symbianCollection.calSession()->CalendarInfoL();
        TRAP_IGNORE(creationTime = getCalInfoPropertyL<TTime>(*calInfoOld, ECreationTime));
        delete calInfoOld;
        setCalInfoPropertyL(calInfo, ECreationTime, creationTime);
        
        // Update the existing collection
        symbianCollection.calSession()->SetCalendarInfoL(*calInfo);
    }
    CleanupStack::PopAndDestroy(calInfo);

    // Update collection information for client
    *collection = symbianCollection.toQOrganizerCollectionL();
#endif //SYMBIAN_CALENDAR_V2
}

bool QOrganizerItemSymbianEngine::removeCollection(
    const QOrganizerCollectionId& collectionId, 
    QOrganizerManager::Error* error)
{
    TRAPD(err, removeCollectionL(collectionId));
    transformError(err, error);
    if (*error == QOrganizerManager::NoError) {
        QOrganizerCollectionChangeSet collectionChangeSet;
        collectionChangeSet.insertRemovedCollection(collectionId);
        collectionChangeSet.emitSignals(this);
    }
    return (*error == QOrganizerManager::NoError);
}

void QOrganizerItemSymbianEngine::removeCollectionL(
    const QOrganizerCollectionId& collectionId)
{
#ifndef SYMBIAN_CALENDAR_V2
    Q_UNUSED(collectionId);
    User::Leave(KErrNotSupported);
#else
    // Dont allow removing the default collection
    if (collectionId == m_defaultCollection.id())
        User::Leave(KErrAccessDenied);
    
    // Find collection
    foreach(const OrganizerSymbianCollection &collection, m_collections) {
        if (collection.id() == collectionId) {
            
            // Get cal info
            CCalCalendarInfo *calInfo = collection.calSession()->CalendarInfoL();
            CleanupStack::PushL(calInfo);
                        
            // Remove the calendar file itself
            TRAPD(err, 
                collection.calSession()->DeleteCalFileL(calInfo->FileNameL()));
            if( err == KErrInUse ) {
                
                // We cannot remove the calendar if we are not the only one
                // who has it open. So instead just disable it and mark it for
                // deletion. The native symbian calendar will remove it
                // during the next startup.
                // TODO: should we try to delete those during startup also?
                calInfo->SetEnabled( EFalse );
                setCalInfoPropertyL(calInfo, ESyncStatus, EFalse);
                setCalInfoPropertyL(calInfo, EMarkAsDelete, ETrue);
                
                // Update modification time
                TTime modificationTime;
                modificationTime.HomeTime();
                setCalInfoPropertyL(calInfo, EModificationTime, modificationTime);
                
                // TODO: Should we remove all entries also? 
                // Client might reopen the calendar before its really deleted.
                            
                // Update calendar info
                collection.calSession()->SetCalendarInfoL( *calInfo );
                }
            else {
                User::LeaveIfError(err);
            }
            CleanupStack::PopAndDestroy(calInfo);

            // Delete the collection
            m_collections.remove(collection.id());
            return;
        }
    }
    User::Leave(KErrNotFound);
#endif // SYMBIAN_CALENDAR_V2
}

QOrganizerItem QOrganizerItemSymbianEngine::compatibleItem(
    const QOrganizerItem& original,
    QOrganizerManager::Error* error) const
{
    *error = QOrganizerManager::NoError;

    if (original.type() == QOrganizerItemType::TypeEvent) {
        QOrganizerEvent event = original;
        if (!event.startDateTime().isValid()) {
            // Event type requires start time in symbian calendar API
            event.setStartDateTime(QDateTime::currentDateTime());
        }
        return event;
    }

    return original;
}

QOrganizerCollection QOrganizerItemSymbianEngine::compatibleCollection(
    const QOrganizerCollection& original, QOrganizerManager::Error* error) const
{
    *error = QOrganizerManager::NoError;

    QOrganizerCollection compatibleCollection = original;

    // Check that the collection has either name or file name. Note: If the
    // file name is missing but name is available, file name will be generated
    // from name.
    if (!original.metaData().contains(OrganizerSymbianCollection::KeyFileName)) {
        if (original.metaData().contains(QOrganizerCollection::KeyName)) {
            // Use collection name as file name
            compatibleCollection.setMetaData(
                OrganizerSymbianCollection::KeyFileName,
                original.metaData(QOrganizerCollection::KeyName));
        } else {
            // Neither file name nor name available -> synthesize a file name
            QString unnamed("Unnamed");
            const int KMaxSynthesizedCount(99);
            for (int i(0); i < KMaxSynthesizedCount; i++) {
                QString synthesizedName = unnamed + QString::number(i);
                if (isCollectionNameAvailable(synthesizedName)) {
                    compatibleCollection.setMetaData(OrganizerSymbianCollection::KeyFileName, synthesizedName);
                    break;
                }
            }
        }
    }

    return compatibleCollection;
}

bool QOrganizerItemSymbianEngine::isCollectionNameAvailable(QString name) const
{
    foreach (OrganizerSymbianCollection collection, m_collections.values()) {
        if (collection.fileName() == name) {
            return false;
        }
    }
    return true;
}

QMap<QString, QOrganizerItemDetailDefinition> 
QOrganizerItemSymbianEngine::detailDefinitions(
    const QString& itemType, QOrganizerManager::Error* error) const
{
    if (m_definition.isEmpty()) {
        // Get all the detail definitions from the base implementation
        m_definition = QOrganizerManagerEngine::schemaDefinitions();
        
        // Modify the base schema to match backend support
        m_itemTransform.modifyBaseSchemaDefinitions(m_definition);
    }
    
    // Check if we support the item type
    if (!m_definition.contains(itemType)) {
        *error = QOrganizerManager::NotSupportedError;
        return QMap<QString, QOrganizerItemDetailDefinition>();
    }
    
    *error = QOrganizerManager::NoError;
    return m_definition.value(itemType);
}

bool QOrganizerItemSymbianEngine::startRequest(
    QOrganizerAbstractRequest* req)
{
    /*
        This is the entry point to the async API.  The request object describes 
        the type of request (switch on req->type()).  Req will not be null when 
        called by the framework.

        Generally, you can queue the request and process them at some later time
        (probably in another thread).

        Once you start a request, call the updateRequestState and/or the
        specific updateXXXXXRequest functions to mark it in the active state.

        If your engine is particularly fast, or the operation involves only in
        memory data, you can process and complete the request here.  That is
        probably not the case, though.

        Note that when the client is threaded, and the request might live on a
        different thread, you might need to be careful with locking.  
        In particular, the request might be deleted while you are still working 
        on it.  In this case, your requestDestroyed function will be called 
        while the request is still valid, and you should block in that function 
        until your worker thread (etc) has been notified not to touch that 
        request any more. 
        
        We plan to provide some boiler plate code that will allow you to:

        1) implement the sync functions, and have the async versions call the 
        sync in another thread

        2) or implement the async versions of the function, and have the sync 
        versions call the async versions.

        It's not ready yet, though.

        Return true if the request can be started, false otherwise.  You can set
        an error in the request if you like.
     */
    return m_requestServiceProviderQueue->startRequest(req);
}

bool QOrganizerItemSymbianEngine::cancelRequest(
    QOrganizerAbstractRequest* req)
{
    /*
        Cancel an in progress async request.  If not possible, return false 
        from here.
    */
    return m_requestServiceProviderQueue->cancelRequest(req);
}

bool QOrganizerItemSymbianEngine::waitForRequestFinished(
    QOrganizerAbstractRequest* req, int msecs)
{
    /*
        Wait for a request to complete (up to a max of msecs milliseconds).

        Return true if the request is finished (including if it was already).  
        False otherwise.

        You should really implement this function, if nothing else than as a 
        delay, since clients may call this in a loop.

        It's best to avoid processing events, if you can, or at least only 
        process non-UI events.
    */
    return m_requestServiceProviderQueue->waitForRequestFinished(req, msecs);
}

void QOrganizerItemSymbianEngine::requestDestroyed(
    QOrganizerAbstractRequest* req)
{
    /*
        This is called when a request is being deleted.  It lets you know:

        1) the client doesn't care about the request any more.  You can still 
        complete it if you feel like it.
        2) you can't reliably access any properties of the request pointer any 
        more. The pointer will be invalid once this function returns.

        This means that if you have a worker thread, you need to let that 
        thread know that the request object is not valid and block until that 
        thread acknowledges it.  One way to do this is to have a QSet<QOIAR*> 
        (or QMap<QOIAR, MyCustomRequestState>) that tracks active requests, and
        insert into that set in startRequest, and remove in requestDestroyed 
        (or when it finishes or is cancelled).  Protect that set/map with a 
        mutex, and make sure you take the mutex in the worker thread before 
        calling any of the QOIAR::updateXXXXXXRequest functions.  And be 
        careful of lock ordering problems :D

    */
        m_requestServiceProviderQueue->requestDestroyed(req);
}

bool QOrganizerItemSymbianEngine::hasFeature(
    QOrganizerManager::ManagerFeature feature, 
    const QString& itemType) const
{
    Q_UNUSED(itemType);
    switch(feature) {
        case QOrganizerManager::MutableDefinitions:
            // We don't support save/remove detail definition
            return false;
        case QOrganizerManager::Anonymous:
            // The engines share the same data
            return false;
        case QOrganizerManager::ChangeLogs:
            // Change logs not supported
            return false;
    }
    return false;
}

bool QOrganizerItemSymbianEngine::isFilterSupported(
    const QOrganizerItemFilter& filter) const
{
    Q_UNUSED(filter);
    // TODO: filtering based on timestamps could be an exception to the rule,
    // i.e. timestamp detail filters should then return true.
    return false;
}

QList<int> QOrganizerItemSymbianEngine::supportedDataTypes() const
{
    QList<int> ret;
    ret << QVariant::String;
    ret << QVariant::Date;
    ret << QVariant::DateTime;
    ret << QVariant::Time;

    return ret;
}

QStringList QOrganizerItemSymbianEngine::supportedItemTypes() const
{
    // Lazy initialization
    if (m_definition.isEmpty()) {
        m_definition = QOrganizerManagerEngine::schemaDefinitions();
        m_itemTransform.modifyBaseSchemaDefinitions(m_definition);
    }
    
    return m_definition.keys();
}

#ifdef SYMBIAN_CALENDAR_V2
void QOrganizerItemSymbianEngine::CalendarInfoChangeNotificationL(
    RPointerArray<CCalFileChangeInfo>& aCalendarInfoChangeEntries)
{
    // TODO: QOrganizerCollectionChangeSet?
    QSet<QOrganizerCollectionId> collectionsAdded;
    QSet<QOrganizerCollectionId> collectionsChanged;
    QSet<QOrganizerCollectionId> collectionsRemoved;
    
    // Loop through changes
    int changeCount = aCalendarInfoChangeEntries.Count();
    for (int i=0; i<changeCount; i++) {

        // Get changed calendar file name
        const TDesC& fileName = aCalendarInfoChangeEntries[i]->FileNameL();
        
        // Try to find matching collection
        OrganizerSymbianCollection collection(this);
        foreach (const OrganizerSymbianCollection &c, m_collections) {
            if (c.fileName() == toQString(fileName))
                collection = c; 
        }
        
        // Check change type
        switch (aCalendarInfoChangeEntries[i]->ChangeType())
        {
        case ECalendarFileCreated:
            if (!collection.isValid()) {
                // A calendar file has been created but not by this manager 
                // instance.
                collection.openL(fileName);
                m_collections.insert(collection.id(), collection);
                collection.createViewsL();
                collectionsAdded << collection.id();
            }
            break;
            
        case ECalendarFileDeleted:
            if (collection.isValid()) {
                // A calendar file has been removed but not by this manager 
                // instance.
                QOrganizerCollectionId id = collection.id();
                m_collections.remove(id);
                collectionsRemoved << id;
            }
            break;
            
        case ECalendarInfoCreated:
            break;
            
        case ECalendarInfoUpdated:
            if (collection.isValid()) {
                if (collection.isMarkedForDeletionL()) {
                    // A calendar file has been marked for deletion but not by 
                    // this manager instance
                    QOrganizerCollectionId id = collection.id();
                    m_collections.remove(id);
                    collectionsRemoved << id;
                    // TODO: Try removing the calendar file?                    
                } else {
                    collectionsChanged << collection.id();
                }
            } else {
                // Calendar file has been modified but we do not have a session 
                // to it.
                collection.openL(fileName);
                
                // Is it marked for deletion?
                if (collection.isMarkedForDeletionL()) {
                    // Something has modified a calendar which is marked for 
                    // deletion.
                } else {
                    // A calendar file which was marked for deletion has been 
                    // taken into use again.
                    m_collections.insert(collection.id(), collection);
                    collection.createViewsL();
                    collectionsAdded << collection.id();
                }
            }
            break;
            
        case ECalendarInfoDeleted:
            break;
            
        default:
            break;
        }
    }
    
    // Emit signals
    if (collectionsAdded.count())
        emit this->collectionsAdded(collectionsAdded.toList());
    if (collectionsChanged.count())
        emit this->collectionsChanged(collectionsChanged.toList());
    if (collectionsRemoved.count())
        emit this->collectionsRemoved(collectionsRemoved.toList());
}
#endif

/*! Transform a Symbian error id to QOrganizerManager::Error.
 *
 * \param symbianError Symbian error.
 * \param QtError Qt error.
 * \return true if there was no error
 *         false if there was an error
*/
bool QOrganizerItemSymbianEngine::transformError(TInt symbianError, QOrganizerManager::Error* qtError)
{
    switch(symbianError)
    {
        case KErrNone:
        {
            *qtError = QOrganizerManager::NoError;
            break;
        }
        case KErrNotFound:
        {
            *qtError = QOrganizerManager::DoesNotExistError;
            break;
        }
        case KErrAlreadyExists:
        {
            *qtError = QOrganizerManager::AlreadyExistsError;
            break;
        }
        case KErrLocked:
        {
            *qtError = QOrganizerManager::LockedError;
            break;
        }
        case KErrAccessDenied:
        case KErrPermissionDenied:
        {
            *qtError = QOrganizerManager::PermissionsError;
            break;
        }
        case KErrNoMemory:
        {
            *qtError = QOrganizerManager::OutOfMemoryError;
            break;
        }
        case KErrNotSupported:
        {
            *qtError = QOrganizerManager::NotSupportedError;
            break;
        }
        case KErrArgument:
        {
            *qtError = QOrganizerManager::BadArgumentError;
            break;
        }
        // KErrInvalidOccurrence is a special error code defined for Qt
        // Organizer API implementation purpose only
        case KErrInvalidOccurrence:
        {
            *qtError = QOrganizerManager::InvalidOccurrenceError;
            break;
        }
        case KErrInvalidItemType:
        {
            *qtError = QOrganizerManager::InvalidItemTypeError;
            break;
        }
        default:
        {
            *qtError = QOrganizerManager::UnspecifiedError;
            break;
        }
    }
    return *qtError == QOrganizerManager::NoError;
}