summaryrefslogtreecommitdiffstats
path: root/plugins/declarative/organizer/qdeclarativeorganizermodel.cpp
blob: cf8dd2fe844670644015899c11ebeb57be7c0101 (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
/****************************************************************************
**
** Copyright (C) 2012 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtDeclarative module of the Qt Toolkit.
**
** $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$
**
****************************************************************************/

#include <qorganizeritemdetails.h>
#include <QtDeclarative/qdeclarativeinfo.h>
#include "qdeclarativeorganizermodel_p.h"
#include "qorganizermanager.h"
#include "qversitreader.h"
#include "qversitwriter.h"
#include "qversitorganizerimporter.h"
#include "qversitorganizerexporter.h"
#include <QFile>

#include "qorganizeritemrequests.h"

static QString urlToLocalFileName(const QUrl& url)
{
   if (!url.isValid()) {
      return url.toString();
   } else if (url.scheme() == "qrc") {
      return url.toString().remove(0, 5).prepend(':');
   } else {
      return url.toLocalFile();
   }

}


class QDeclarativeOrganizerModelPrivate
{
public:
    QDeclarativeOrganizerModelPrivate()
        :m_manager(0),
        m_fetchHint(0),
        m_filter(0),
        m_fetchRequest(0),
        m_occurrenceFetchRequest(0),
        m_startPeriod(QDateTime::currentDateTime()),
        m_endPeriod(QDateTime::currentDateTime()),
        m_autoUpdate(true),
        m_updatePending(false),
        m_componentCompleted(false)
    {
    }
    ~QDeclarativeOrganizerModelPrivate()
    {
        if (m_manager)
            delete m_manager;
    }

    QList<QDeclarativeOrganizerItem*> m_items;
    QMap<QString, QDeclarativeOrganizerItem*> m_itemMap;
    QOrganizerManager* m_manager;
    QDeclarativeOrganizerItemFetchHint* m_fetchHint;
    QList<QOrganizerItemSortOrder> m_sortOrders;
    QList<QDeclarativeOrganizerItemSortOrder*> m_declarativeSortOrders;
    QDeclarativeOrganizerItemFilter* m_filter;
    QOrganizerItemFetchRequest* m_fetchRequest;
    QOrganizerItemOccurrenceFetchRequest* m_occurrenceFetchRequest;
    QList<QString> m_updatedItemIds;
    QStringList m_importProfiles;
    QVersitReader m_reader;
    QVersitWriter m_writer;
    QDateTime m_startPeriod;
    QDateTime m_endPeriod;

    bool m_autoUpdate;
    bool m_updatePending;
    bool m_componentCompleted;
};

/*!
    \qmlclass OrganizerModel QDeclarativeOrganizerModel
    \brief The OrganizerModel element provides access to organizer items from the organizer store.
    \ingroup qml-organizer
    \since Mobility 1.1

    This element is part of the \bold{QtMobility.organizer 1.1} module.

    OrganizerModel provides a model of organizer items from the organizer store.
    The contents of the model can be specified with \l filter, \l sortOrders and \l fetchHint properties.
    Whether the model is automatically updated when the store or \l organizer item changes, can be
    controlled with \l OrganizerModel::autoUpdate property.

    There are two ways of accessing the organizer item data: via the model by using views and delegates,
    or alternatively via \l items list property. Of the two, the model access is preferred.
    Direct list access (i.e. non-model) is not guaranteed to be in order set by \l sortOrder.

    At the moment the model roles provided by OrganizerModel are \c display and \c item.
    Through the \c item role can access any data provided by the OrganizerItem element.


    \note Both the \c startPeriod and \c endPeriod are set by default to the current time (when the OrganizerModel was created).
     In most cases, both (or at least one) of the startPeriod and endPeriod should be set; otherwise, the OrganizerModel will contain
     zero items because the \c startPeriod and \c endPeriod are the same value. For example, if only \c endPeriod is provided,
     the OrganizerModel will contain all items from now (the time of the OrganizerModel's creation) to the \c endPeriod time.

    \sa OrganizerItem, {QOrganizerManager}
*/

QDeclarativeOrganizerModel::QDeclarativeOrganizerModel(QObject *parent) :
    QAbstractListModel(parent),
    d(new QDeclarativeOrganizerModelPrivate)
{
    QHash<int, QByteArray> roleNames;
    roleNames = QAbstractItemModel::roleNames();
    roleNames.insert(OrganizerItemRole, "item");
    setRoleNames(roleNames);

    connect(this, SIGNAL(managerChanged()), SLOT(doUpdate()));
    connect(this, SIGNAL(filterChanged()), SLOT(doUpdate()));
    connect(this, SIGNAL(fetchHintChanged()), SLOT(doUpdate()));
    connect(this, SIGNAL(sortOrdersChanged()), SLOT(doUpdate()));
    connect(this, SIGNAL(startPeriodChanged()), SLOT(doUpdate()));
    connect(this, SIGNAL(endPeriodChanged()), SLOT(doUpdate()));

    //import vcard
    connect(&d->m_reader, SIGNAL(stateChanged(QVersitReader::State)), this, SLOT(startImport(QVersitReader::State)));
    connect(&d->m_writer, SIGNAL(stateChanged(QVersitWriter::State)), this, SLOT(itemsExported(QVersitWriter::State)));
}

/*!
  \qmlproperty string OrganizerModel::manager
  \since Mobility 1.1

  This property holds the manager name or manager uri of the organizer backend engine.
  The manager uri format: qtorganizer:<managerid>:<key>=<value>&<key>=<value>.

  For example, memory organizer engine has an optional id parameter, if user want to
  share the same memory engine with multiple OrganizerModel instances, the manager property
  should declared like this:
  \code
    model : OrganizerModel {
       manager:"qtorganizer:memory:id=organizer1
    }
  \endcode

  instead of just the manager name:
  \code
    model : OrganizerModel {
       manager:"memory"
    }
  \endcode

  \sa QOrganizerManager::fromUri()
  */
QString QDeclarativeOrganizerModel::manager() const
{
    if (d->m_manager)
        return d->m_manager->managerUri();
    return QString();
}

/*!
  \qmlproperty string OrganizerModel::managerName
  \since Mobility 1.1

  This property holds the manager name of the organizer backend engine.
  This property is read only.
  \sa QOrganizerManager::fromUri()
  */
QString QDeclarativeOrganizerModel::managerName() const
{
    if (d->m_manager)
        return d->m_manager->managerName();
    return QString();
}

/*!
  \qmlproperty list<string> OrganizerModel::availableManagers
  \since Mobility 1.1

  This property holds the list of available manager names.
  This property is read only.
  */
QStringList QDeclarativeOrganizerModel::availableManagers() const
{
    return QOrganizerManager::availableManagers();
}

/*!
  \qmlproperty bool OrganizerModel::autoUpdate
  \since Mobility 1.1

  This property indicates whether or not the organizer model should be updated automatically, default value is true.

  \sa OrganizerModel::update()
  */
void QDeclarativeOrganizerModel::setAutoUpdate(bool autoUpdate)
{
    if (autoUpdate == d->m_autoUpdate)
        return;
    d->m_autoUpdate = autoUpdate;
    emit autoUpdateChanged();
}

bool QDeclarativeOrganizerModel::autoUpdate() const
{
    return d->m_autoUpdate;
}

/*!
  \qmlmethod OrganizerModel::update()
  \since Mobility 1.1

  Manually update the organizer model content.

  \sa OrganizerModel::autoUpdate
  */
void QDeclarativeOrganizerModel::update()
{
    if (!d->m_componentCompleted || d->m_updatePending)
        return;

    d->m_updatePending = true; // Disallow possible duplicate request triggering
    QMetaObject::invokeMethod(this, "fetchAgain", Qt::QueuedConnection);
}

void QDeclarativeOrganizerModel::doUpdate()
{
    if (d->m_autoUpdate)
        update();
}

/*!
  \qmlmethod OrganizerModel::cancelUpdate()
  \since Mobility 1.1

  Cancel the running organizer model content update request.

  \sa OrganizerModel::autoUpdate  OrganizerModel::update
  */
void QDeclarativeOrganizerModel::cancelUpdate()
{
    if (d->m_fetchRequest) {
        d->m_fetchRequest->cancel();
        d->m_fetchRequest->deleteLater();
        d->m_fetchRequest = 0;
        d->m_updatePending = false;
    }
}
/*!
  \qmlproperty date OrganizerModel::startPeriod
  \since Mobility 1.1

  This property holds the start date and time period used by the organizer model to fetch organizer items.
  The default value is the datetime of OrganizerModel creation.
  */
QDateTime QDeclarativeOrganizerModel::startPeriod() const
{
    return d->m_startPeriod;
}
void QDeclarativeOrganizerModel::setStartPeriod(const QDateTime& start)
{
    if (start != d->m_startPeriod) {
        d->m_startPeriod = start;
        emit startPeriodChanged();
    }
}

/*!
  \qmlproperty date OrganizerModel::endPeriod
  \since Mobility 1.1

  This property holds the end date and time period used by the organizer model to fetch organizer items.
  The default value is the datetime of OrganizerModel creation.
  */
QDateTime QDeclarativeOrganizerModel::endPeriod() const
{
    return d->m_endPeriod;
}
void QDeclarativeOrganizerModel::setEndPeriod(const QDateTime& end)
{
    if (end != d->m_endPeriod) {
        d->m_endPeriod = end;
        emit endPeriodChanged();
    }
}

/*!
  \qmlmethod OrganizerModel::importItems(url url, list<string> profiles)
  \since Mobility 1.1

  Import organizer items from a vcalendar by the given \a url and optional \a profiles.
  */
void QDeclarativeOrganizerModel::importItems(const QUrl& url, const QStringList& profiles)
{
   d->m_importProfiles = profiles;
   //TODO: need to allow download vcard from network
   QFile*  file = new QFile(urlToLocalFileName(url));
   bool ok = file->open(QIODevice::ReadOnly);
   if (ok) {
      d->m_reader.setDevice(file);
      d->m_reader.startReading();
   }
}

/*!
  \qmlmethod OrganizerModel::exportItems(url url, list<string> profiles)
  \since Mobility 1.1
  Export organizer items into a vcalendar file to the given \a url by optional \a profiles.
  At the moment only the local file url is supported in export method.
  */
void QDeclarativeOrganizerModel::exportItems(const QUrl& url, const QStringList& profiles)
{
    QString profile = profiles.isEmpty()? QString() : profiles.at(0);

    QVersitOrganizerExporter exporter(profile);
    QList<QOrganizerItem> items;
    foreach (QDeclarativeOrganizerItem* di, d->m_items) {
        items.append(di->item());
    }

    exporter.exportItems(items, QVersitDocument::VCard30Type);
    QVersitDocument document = exporter.document();
    QFile* file = new QFile(urlToLocalFileName(url));
    bool ok = file->open(QIODevice::ReadWrite);
    if (ok) {
       d->m_writer.setDevice(file);
       d->m_writer.startWriting(document);
    }
}

void QDeclarativeOrganizerModel::itemsExported(QVersitWriter::State state)
{
    if (state == QVersitWriter::FinishedState || state == QVersitWriter::CanceledState) {
         delete d->m_writer.device();
         d->m_writer.setDevice(0);
    }
}

int QDeclarativeOrganizerModel::rowCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return d->m_items.count();
}

void QDeclarativeOrganizerModel::setManager(const QString& managerName)
{
    if (d->m_manager) {
        delete d->m_manager;
    }

    if (managerName.startsWith("qtorganizer:")) {
        d->m_manager = QOrganizerManager::fromUri(managerName, this);
    } else {
        d->m_manager = new QOrganizerManager(managerName, QMap<QString, QString>(), this);
    }

    connect(d->m_manager, SIGNAL(dataChanged()), this, SLOT(update()));
    connect(d->m_manager, SIGNAL(itemsAdded(QList<QOrganizerItemId>)), this, SLOT(update()));
    connect(d->m_manager, SIGNAL(itemsRemoved(QList<QOrganizerItemId>)), this, SLOT(itemsRemoved(QList<QOrganizerItemId>)));
    connect(d->m_manager, SIGNAL(itemsChanged(QList<QOrganizerItemId>)), this, SLOT(itemsChanged(QList<QOrganizerItemId>)));
    emit managerChanged();
}

void QDeclarativeOrganizerModel::componentComplete()
{
    d->m_componentCompleted = true;
    if (!d->m_manager)
        setManager(QString());

    if (d->m_autoUpdate)
        update();
}
/*!
  \qmlproperty Filter OrganizerModel::filter
  \since Mobility 1.1

  This property holds the filter instance used by the organizer model.

  \sa Filter
  */
QDeclarativeOrganizerItemFilter* QDeclarativeOrganizerModel::filter() const
{
    return d->m_filter;
}

void QDeclarativeOrganizerModel::setFilter(QDeclarativeOrganizerItemFilter* filter)
{
    if (filter && filter != d->m_filter) {
        if (d->m_filter)
            delete d->m_filter;
        d->m_filter = filter;
        connect(d->m_filter, SIGNAL(filterChanged()), this, SIGNAL(filterChanged()));
        emit filterChanged();
    }
}

/*!
  \qmlproperty FetchHint OrganizerModel::fetchHint
  \since Mobility 1.1

  This property holds the fetch hint instance used by the organizer model.

  \sa FetchHint
  */
QDeclarativeOrganizerItemFetchHint* QDeclarativeOrganizerModel::fetchHint() const
{
    return d->m_fetchHint;
}

void QDeclarativeOrganizerModel::setFetchHint(QDeclarativeOrganizerItemFetchHint* fetchHint)
{
    if (fetchHint && fetchHint != d->m_fetchHint) {
        if (d->m_fetchHint)
            delete d->m_fetchHint;
        d->m_fetchHint = fetchHint;
        connect(d->m_fetchHint, SIGNAL(fetchHintChanged()), this, SIGNAL(fetchHintChanged()));
        emit fetchHintChanged();
    }
}
/*!
  \qmlproperty int OrganizerModel::itemCount
  \since Mobility 1.1

  This property holds the size of organizer items the OrganizerModel currently holds.

  This property is read only.
  */
int QDeclarativeOrganizerModel::itemCount() const
{
    return d->m_items.size();
}
/*!
  \qmlproperty string OrganizerModel::error
  \since Mobility 1.1

  This property holds the latest error code returned by the organizer manager.

  This property is read only.
  */
QString QDeclarativeOrganizerModel::error() const
{
    if (d->m_manager) {
        switch (d->m_manager->error()) {
        case QOrganizerManager::DoesNotExistError:
            return QLatin1String("DoesNotExist");
        case QOrganizerManager::AlreadyExistsError:
            return QLatin1String("AlreadyExists");
        case QOrganizerManager::InvalidDetailError:
            return QLatin1String("InvalidDetail");
        case QOrganizerManager::InvalidCollectionError:
            return QLatin1String("InvalidCollection");
        case QOrganizerManager::LockedError:
            return QLatin1String("LockedError");
        case QOrganizerManager::DetailAccessError:
            return QLatin1String("DetailAccessError");
        case QOrganizerManager::PermissionsError:
            return QLatin1String("PermissionsError");
        case QOrganizerManager::OutOfMemoryError:
            return QLatin1String("OutOfMemory");
        case QOrganizerManager::NotSupportedError:
            return QLatin1String("NotSupported");
        case QOrganizerManager::BadArgumentError:
            return QLatin1String("BadArgument");
        case QOrganizerManager::UnspecifiedError:
            return QLatin1String("UnspecifiedError");
        case QOrganizerManager::VersionMismatchError:
            return QLatin1String("VersionMismatch");
        case QOrganizerManager::LimitReachedError:
            return QLatin1String("LimitReached");
        case QOrganizerManager::InvalidItemTypeError:
            return QLatin1String("InvalidItemType");
            case QOrganizerManager::InvalidOccurrenceError:
                return QLatin1String("InvalidOccurrence");
        default:
            break;
        }
    }
    return QLatin1String("NoError");
}

/*!
  \qmlproperty list<SortOrder> OrganizerModel::sortOrders
  \since Mobility 1.1

  This property holds a list of sort orders used by the organizer model.

  \sa SortOrder
  */
QDeclarativeListProperty<QDeclarativeOrganizerItemSortOrder> QDeclarativeOrganizerModel::sortOrders()
{
    return QDeclarativeListProperty<QDeclarativeOrganizerItemSortOrder>(this,
                                                                        0,
                                                                        sortOrder_append,
                                                                        sortOrder_count,
                                                                        sortOrder_at,
                                                                        sortOrder_clear);
}

void QDeclarativeOrganizerModel::startImport(QVersitReader::State state)
{
    if (state == QVersitReader::FinishedState || state == QVersitReader::CanceledState) {
        if (!d->m_reader.results().isEmpty()) {
            QVersitOrganizerImporter importer;

            importer.importDocument(d->m_reader.results().at(0));
            QList<QOrganizerItem> items = importer.items();
            delete d->m_reader.device();
            d->m_reader.setDevice(0);


            if (d->m_manager) {
                if (d->m_manager->saveItems(&items)) {
                    update();
                }
            }
        }
    }
}

bool QDeclarativeOrganizerModel::itemHasReccurence(const QOrganizerItem& oi) const
{
    if (oi.type() == QOrganizerItemType::TypeEvent || oi.type() == QOrganizerItemType::TypeTodo) {
        QOrganizerItemRecurrence recur = oi.detail(QOrganizerItemRecurrence::DefinitionName);
        return !recur.recurrenceDates().isEmpty() || !recur.recurrenceRules().isEmpty();
    }

    return false;
}
void QDeclarativeOrganizerModel::fetchOccurrences(const QOrganizerItem& item)
{
    QOrganizerItemOccurrenceFetchRequest* req =  new QOrganizerItemOccurrenceFetchRequest(this);
    req->setManager(d->m_manager);
    req->setStartDate(d->m_startPeriod);
    req->setEndDate(d->m_endPeriod);
    req->setFetchHint(d->m_fetchHint ? d->m_fetchHint->fetchHint() : QOrganizerItemFetchHint());
    req->setParentItem(item);

    connect(req, SIGNAL(stateChanged(QOrganizerAbstractRequest::State)), this, SLOT(requestUpdated()));
    req->start();

}

void QDeclarativeOrganizerModel::addSorted(QDeclarativeOrganizerItem* item)
{
    removeItemsFromModel(QList<QString>() << item->itemId());
    int idx = itemIndex(item);
    beginInsertRows(QModelIndex(), idx, idx + 1);
    d->m_items.insert(idx, item);
    endInsertRows();
    d->m_itemMap.insert(item->itemId(), item);

    if (itemHasReccurence(item->item())) {
        foreach (QDeclarativeOrganizerItem* di, d->m_items) {
            if (di->isOccurrence()) {
                 QOrganizerItemParent oip = di->item().detail<QOrganizerItemParent>();
                 if (oip.parentId() == item->item().id()) {
                     //delete this occurrence item, we will refetch it
                     d->m_itemMap.remove(di->itemId());
                     d->m_items.removeOne(di);
                     di->deleteLater();
                 }
            }
        }

        fetchOccurrences(item->item());
    }
}

int QDeclarativeOrganizerModel::itemIndex(const QDeclarativeOrganizerItem* item)
{
    if (d->m_sortOrders.count() > 0) {
        for (int i = 0; i < d->m_items.size(); i++) {
            // check to see if the new item should be inserted here
            int comparison = QOrganizerManagerEngine::compareItem(d->m_items.at(i)->item(),
                                                                  item->item(),
                                                                  d->m_sortOrders);
            if (comparison > 0) {
                return i;
            }
        }
    }
    return d->m_items.size();
}

void QDeclarativeOrganizerModel::clearItems()
{
    foreach (QDeclarativeOrganizerItem* di, d->m_items)
        di->deleteLater();
    d->m_items.clear();
    d->m_itemMap.clear();
}

QDeclarativeOrganizerItem* QDeclarativeOrganizerModel::createItem(const QOrganizerItem& item)
{
    QDeclarativeOrganizerItem* di;
    if (item.type() == QOrganizerItemType::TypeEvent)
        di = new QDeclarativeOrganizerEvent(this);
    else if (item.type() == QOrganizerItemType::TypeEventOccurrence)
        di = new QDeclarativeOrganizerEventOccurrence(this);
    else if (item.type() == QOrganizerItemType::TypeTodo)
        di = new QDeclarativeOrganizerTodo(this);
    else if (item.type() == QOrganizerItemType::TypeTodoOccurrence)
        di = new QDeclarativeOrganizerTodoOccurrence(this);
    else if (item.type() == QOrganizerItemType::TypeJournal)
        di = new QDeclarativeOrganizerJournal(this);
    else if (item.type() == QOrganizerItemType::TypeNote)
        di = new QDeclarativeOrganizerNote(this);
    else
        di = new QDeclarativeOrganizerItem(this);
    di->setItem(item);
    di->setDetailDefinitions(d->m_manager->detailDefinitions(item.type()));
    return di;
}

/*!
  \qmlmethod OrganizerModel::fetchItems(list<QString> itemIds)
  \since Mobility 1.1
  Fetch a list of organizer items from the organizer store by given \a itemIds.
  */
void QDeclarativeOrganizerModel::fetchItems(const QList<QString>& itemIds)
{
    d->m_updatedItemIds = itemIds;
    d->m_updatePending = true;
    QMetaObject::invokeMethod(this, "fetchAgain", Qt::QueuedConnection);
}

/*!
  \qmlmethod bool OrganizerModel::containsItems(date start, date end)
  \since Mobility 1.1
  Returns true if there is at least one OrganizerItem between the given date range.
  Both the \a start and  \a end parameters are optional, if no \a end parameter, returns true
  if there are item(s) after \a start, if neither start nor end date time provided, returns true if
  items in the current model is not empty, otherwise return false.
  \sa itemIds()
  */
bool QDeclarativeOrganizerModel::containsItems(QDateTime start, QDateTime end)
{
    return !itemIds(start, end).isEmpty();
}

/*!
  \qmlmethod OrganizerItem OrganizerModel::item(string itemId)
  \since Mobility 1.1
  Returns the OrganizerItem object which item id is the given \a itemId.

  */
QDeclarativeOrganizerItem* QDeclarativeOrganizerModel::item(const QString& id)
{

    if (d->m_itemMap.contains(id))
        return d->m_itemMap.value(id);
    return 0;
}

/*!
  \qmlmethod list<string> OrganizerModel::itemIds(date start, date end)
  \since Mobility 1.1
  Returns the list of organizer item ids between the given date range \a start and \a end,
  Both the \a start and  \a end parameters are optional, if no \a end parameter, returns all
  item ids from \a start, if neither start nor end date time provided, returns all item ids in the
  current model.

  \sa containsItems()
  */
QStringList QDeclarativeOrganizerModel::itemIds(QDateTime start, QDateTime end)
{
    //TODO: quick search this
    QStringList ids;
    if (!end.isNull()){
        // both start date and end date are valid
        foreach (QDeclarativeOrganizerItem* item, d->m_items) {
            if ( (item->itemStartTime() >= start && item->itemStartTime() <= end)
                 ||
                 (item->itemEndTime() >= start && item->itemEndTime() <= end)
                 ||
                 (item->itemEndTime() > end && item->itemStartTime() < start))
                ids << item->itemId();
        }
    }else if (!start.isNull()){
        // only a valid start date is valid
            foreach (QDeclarativeOrganizerItem* item, d->m_items) {
                if (item->itemStartTime() >= start)
                        ids << item->itemId();
            }
    }else{
        // neither start nor end date is valid
        foreach (QDeclarativeOrganizerItem* item, d->m_items)
            ids << item->itemId();
    }
    return ids;
}

void QDeclarativeOrganizerModel::fetchAgain()
{
    cancelUpdate();
    if (d->m_updatedItemIds.isEmpty()) //fetch all items
        clearItems();

    d->m_fetchRequest  = new QOrganizerItemFetchRequest(this);
    d->m_fetchRequest->setManager(d->m_manager);
    d->m_fetchRequest->setSorting(d->m_sortOrders);
    d->m_fetchRequest->setStartDate(d->m_startPeriod);
    d->m_fetchRequest->setEndDate(d->m_endPeriod);

    if (!d->m_updatedItemIds.isEmpty()) {
        QOrganizerItemIdFilter f;
        QList<QOrganizerItemId> ids;
        foreach (const QString& id, d->m_updatedItemIds) {
            ids << QOrganizerItemId::fromString(id);
        }

        f.setIds(ids);
        d->m_fetchRequest->setFilter(f);
        d->m_updatedItemIds.clear();
    } else if (d->m_filter){
        d->m_fetchRequest->setFilter(d->m_filter->filter());
    } else {
        d->m_fetchRequest->setFilter(QOrganizerItemFilter());
    }

    d->m_fetchRequest->setFetchHint(d->m_fetchHint ? d->m_fetchHint->fetchHint() : QOrganizerItemFetchHint());

    connect(d->m_fetchRequest, SIGNAL(stateChanged(QOrganizerAbstractRequest::State)), this, SLOT(requestUpdated()));
    d->m_fetchRequest->start();
}

/*
  This slot function is connected with item fetch requests and item occurrence fetch requests,
  so the QObject::sender() must be checked for the right sender type.
  During update() function, the fetchAgain() will be invoked, inside fetchAgain(), a QOrganizerItemFetchRequest object
  is created and started, when this fetch request finished, this requestUpdate() slot will be invoked for the first time.
  Then check each of the organizer items returned by the item fetch request, if the item is a recurrence item,
  a QOrganizerItemOccurrenceFetchRequest object will be created and started. When each of these occurrence fetch requests
  finishes, this requestUpdated() slot will be invoked again and insert the returned occurrence items into the d->m_items
  list.
  */
void QDeclarativeOrganizerModel::requestUpdated()
{
    QList<QOrganizerItem> items;
    QOrganizerItemFetchRequest* ifr = qobject_cast<QOrganizerItemFetchRequest*>(QObject::sender());
    if (ifr && ifr->isFinished()) {
        items = ifr->items();
        ifr->deleteLater();
        d->m_fetchRequest = 0;
        d->m_updatePending = false;
    } else {
        QOrganizerItemOccurrenceFetchRequest* iofr = qobject_cast<QOrganizerItemOccurrenceFetchRequest*>(QObject::sender());
        if (iofr && iofr->isFinished()) {
            items = iofr->itemOccurrences();
            iofr->deleteLater();
        }
    }

    if (!items.isEmpty()) {
        if (d->m_items.isEmpty()) {
            QDeclarativeOrganizerItem* di;
            foreach (const QOrganizerItem& item, items) {
                di = createItem(item);
                addSorted(di);
            }
        } else {
            //Partial updating, insert the fetched items into the the exist item list.
            foreach (const QOrganizerItem& item, items) {
                QDeclarativeOrganizerItem* di;
                if (d->m_itemMap.contains(item.id().toString())) {
                    di = d->m_itemMap.value(item.id().toString());
                    di->setItem(item);
                } else {
                    di = createItem(item);
                }
                addSorted(di);
            }
        }

        emit modelChanged();
        emit errorChanged();
    }
}

/*!
  \qmlmethod OrganizerModel::saveItem(OrganizerItem item)
  Saves the given \a item into the organizer backend.

  \since Mobility 1.1
*/
void QDeclarativeOrganizerModel::saveItem(QDeclarativeOrganizerItem* di)
{
    if (di) {
        QOrganizerItem item = di->item();
        QOrganizerItemSaveRequest* req = new QOrganizerItemSaveRequest(this);
        req->setManager(d->m_manager);
        req->setItem(item);

        connect(req,SIGNAL(stateChanged(QOrganizerAbstractRequest::State)), this, SLOT(itemsSaved()));

        req->start();
    }
}

void QDeclarativeOrganizerModel::itemsSaved()
{
    QOrganizerItemSaveRequest* req = qobject_cast<QOrganizerItemSaveRequest*>(QObject::sender());
    if (req->isFinished()) {
        if (req->error() == QOrganizerManager::NoError) {
            QList<QOrganizerItem> items = req->items();
            QDeclarativeOrganizerItem* di;
            foreach (const QOrganizerItem& item, items) {
                QString itemId = item.id().toString();
                if (d->m_itemMap.contains(itemId)) {
                    di = d->m_itemMap.value(itemId);
                    di->setItem(item);
                } else {
                    //new saved item
                    di = createItem(item);
                    d->m_itemMap.insert(itemId, di);
                    beginInsertRows(QModelIndex(), d->m_items.count(), d->m_items.count());
                    d->m_items.append(di);
                    endInsertRows();
                }
                addSorted(di);
            }
        }

        req->deleteLater();
        emit errorChanged();
    }
}


/*!
  \qmlmethod OrganizerModel::removeItem(string itemId)
  \since Mobility 1.1
  Removes the organizer item with the given \a itemId from the backend.

  */
void QDeclarativeOrganizerModel::removeItem(const QString& id)
{
    QList<QString> ids;
    ids << id;
    removeItems(ids);
}

/*!
  \qmlmethod OrganizerModel::removeItems(list<string> itemId)
  \since Mobility 1.1
  Removes the organizer items with the given \a ids from the backend.

*/
void QDeclarativeOrganizerModel::removeItems(const QList<QString>& ids)
{
    QOrganizerItemRemoveRequest* req = new QOrganizerItemRemoveRequest(this);
    req->setManager(d->m_manager);
    QList<QOrganizerItemId> oids;

    foreach (const QString& id, ids) {
        if (id.startsWith(QString("qtorganizer:occurrence"))) {
            qmlInfo(this) << tr("Can't remove an occurrence item, please modify the parent item's recurrence rule instead!");
            continue;
        }
        QOrganizerItemId itemId = QOrganizerItemId::fromString(id);
        if (!itemId.isNull()) {
             oids.append(itemId);
        }
    }

    req->setItemIds(oids);

    connect(req,SIGNAL(stateChanged(QOrganizerAbstractRequest::State)), this, SLOT(itemsRemoved()));

    req->start();
}

void QDeclarativeOrganizerModel::itemsChanged(const QList<QOrganizerItemId>& ids)
{
    if (d->m_autoUpdate) {
        QList<QString> updatedIds;
        foreach (const QOrganizerItemId& id, ids) {
            if (d->m_itemMap.contains(id.toString())) {
                updatedIds << id.toString();
            }
        }

        if (updatedIds.count() > 0)
            fetchItems(updatedIds);
    }
}

void QDeclarativeOrganizerModel::itemsRemoved()
{
    if (d->m_autoUpdate) {
        QOrganizerItemRemoveRequest* req = qobject_cast<QOrganizerItemRemoveRequest*>(QObject::sender());


        if (req->isFinished()) {
            QList<QOrganizerItemId> ids = req->itemIds();
            QList<int> errorIds = req->errorMap().keys();
            QList<QOrganizerItemId> removedIds;
            for (int i = 0; i < ids.count(); i++) {
                if (!errorIds.contains(i))
                    removedIds << ids.at(i);
            }
            if (!removedIds.isEmpty())
                itemsRemoved(removedIds);
            req->deleteLater();
        }
    }
}

void QDeclarativeOrganizerModel::removeItemsFromModel(const QList<QString>& ids)
{
    bool emitSignal = false;
    foreach (const QString& itemId, ids) {
        if (d->m_itemMap.contains(itemId)) {
            int row = 0;
            //TODO:need a fast lookup
            for (; row < d->m_items.count(); row++) {
                if (d->m_items.at(row)->itemId() == itemId)
                    break;
            }

            if (row < d->m_items.count()) {
                beginRemoveRows(QModelIndex(), row, row);
                d->m_items.removeAt(row);
                d->m_itemMap.remove(itemId);
                endRemoveRows();
                emitSignal = true;
            }
        }
    }
    emit errorChanged();
    if (emitSignal)
        emit modelChanged();
}

void QDeclarativeOrganizerModel::itemsRemoved(const QList<QOrganizerItemId>& ids)
{
    if (!ids.isEmpty()) {
        QList<QString> idStrings;
        foreach (const QOrganizerItemId& id, ids) {
            idStrings << id.toString();
        }
        removeItemsFromModel(idStrings);
    }
}



QVariant QDeclarativeOrganizerModel::data(const QModelIndex &index, int role) const
{
    //Check if QList itme's index is valid before access it, index should be between 0 and count - 1
    if (index.row() < 0 || index.row() >= d->m_items.count()) {
        return QVariant();
    }

    QDeclarativeOrganizerItem* di = d->m_items.at(index.row());
    Q_ASSERT(di);
    QOrganizerItem item = di->item();
    switch(role) {
        case Qt::DisplayRole:
            return item.displayLabel();
        case Qt::DecorationRole:
            //return pixmap for this item type
        case OrganizerItemRole:
            return QVariant::fromValue(di);
    }
    return QVariant();
}

/*!
  \qmlproperty list<OrganizerItem> OrganizerModel::items
  \since Mobility 1.1

  This property holds a list of organizer items in the organizer model.

  \sa OrganizerItem
  */
QDeclarativeListProperty<QDeclarativeOrganizerItem> QDeclarativeOrganizerModel::items()
{
    return QDeclarativeListProperty<QDeclarativeOrganizerItem>(this, 0, item_append, item_count, item_at, item_clear);
}

/*!
  \qmlproperty list<OrganizerItem> OrganizerModel::occurrences
  \since Mobility 1.1

  This property holds a list of event or todo occurrence items in the organizer model.
  \note This property is not currently supported yet.

  \sa Event, Todo, EventOccurrence, TodoOccurrence
  */
QDeclarativeListProperty<QDeclarativeOrganizerItem> QDeclarativeOrganizerModel::occurrences()
{
    //TODO:XXX
    qmlInfo(this) << tr("OrganizerModel: occurrences is not currently supported.");
    return QDeclarativeListProperty<QDeclarativeOrganizerItem>();
}

/*!
  \qmlproperty list<OrganizerItem> OrganizerModel::events
  \since Mobility 1.1

  This property holds a list of events in the organizer model.

  \sa Event
  */
QDeclarativeListProperty<QDeclarativeOrganizerItem> QDeclarativeOrganizerModel::events()
{
    void* d = const_cast<char*>(QOrganizerItemType::TypeEvent.latin1());
    return QDeclarativeListProperty<QDeclarativeOrganizerItem>(this, d, item_append, item_count, item_at, item_clear);
}

/*!
  \qmlproperty list<OrganizerItem> OrganizerModel::eventOccurrences
  \since Mobility 1.1

  This property holds a list of event occurrences in the organizer model.

  \sa EventOccurrence
  */
QDeclarativeListProperty<QDeclarativeOrganizerItem> QDeclarativeOrganizerModel::eventOccurrences()
{
    void* d = const_cast<char*>(QOrganizerItemType::TypeEventOccurrence.latin1());
    return QDeclarativeListProperty<QDeclarativeOrganizerItem>(this, d, item_append, item_count, item_at, item_clear);
}

/*!
  \qmlproperty list<OrganizerItem> OrganizerModel::todos
  \since Mobility 1.1

  This property holds a list of todos in the organizer model.

  \sa Todo
  */
QDeclarativeListProperty<QDeclarativeOrganizerItem> QDeclarativeOrganizerModel::todos()
{
    void* d = const_cast<char*>(QOrganizerItemType::TypeTodo.latin1());
    return QDeclarativeListProperty<QDeclarativeOrganizerItem>(this, d, item_append, item_count, item_at, item_clear);
}

/*!
  \qmlproperty list<OrganizerItem> OrganizerModel::todoOccurrences
  \since Mobility 1.1

  This property holds a list of todo occurrences in the organizer model.

  \sa TodoOccurrence
  */
QDeclarativeListProperty<QDeclarativeOrganizerItem> QDeclarativeOrganizerModel::todoOccurrences()
{
    void* d = const_cast<char*>(QOrganizerItemType::TypeTodoOccurrence.latin1());
    return QDeclarativeListProperty<QDeclarativeOrganizerItem>(this, d, item_append, item_count, item_at, item_clear);
}

/*!
  \qmlproperty list<OrganizerItem> OrganizerModel::journals
  \since Mobility 1.1

  This property holds a list of journal items in the organizer model.

  \sa Journal
  */
QDeclarativeListProperty<QDeclarativeOrganizerItem> QDeclarativeOrganizerModel::journals()
{
    void* d = const_cast<char*>(QOrganizerItemType::TypeJournal.latin1());
    return QDeclarativeListProperty<QDeclarativeOrganizerItem>(this, d, item_append, item_count, item_at, item_clear);
}


/*!
  \qmlproperty list<OrganizerItem> OrganizerModel::notes
  \since Mobility 1.1

  This property holds a list of note items in the organizer model.

  \sa Note
  */
QDeclarativeListProperty<QDeclarativeOrganizerItem> QDeclarativeOrganizerModel::notes()
{
    void* d = const_cast<char*>(QOrganizerItemType::TypeNote.latin1());
    return QDeclarativeListProperty<QDeclarativeOrganizerItem>(this, d, item_append, item_count, item_at, item_clear);
}


void QDeclarativeOrganizerModel::item_append(QDeclarativeListProperty<QDeclarativeOrganizerItem> *p, QDeclarativeOrganizerItem *item)
{
    Q_UNUSED(p);
    Q_UNUSED(item);
    qmlInfo(0) << tr("OrganizerModel: appending items is not currently supported");
}

int  QDeclarativeOrganizerModel::item_count(QDeclarativeListProperty<QDeclarativeOrganizerItem> *p)
{
    QString type((const char*)(p->data));
    QDeclarativeOrganizerModel* model = qobject_cast<QDeclarativeOrganizerModel*>(p->object);
    int count = 0;

    if (model) {
        if (!type.isEmpty()) {
            foreach (const QDeclarativeOrganizerItem* item, model->d->m_items) {
                if (item->item().type() == type)
                    count++;
            }
        } else {
            return model->d->m_items.count();
        }
    }
    return count;
}

QDeclarativeOrganizerItem * QDeclarativeOrganizerModel::item_at(QDeclarativeListProperty<QDeclarativeOrganizerItem> *p, int idx)
{
    QString type((const char*)(p->data));
    QDeclarativeOrganizerModel* model = qobject_cast<QDeclarativeOrganizerModel*>(p->object);

    QDeclarativeOrganizerItem* item = 0;
    if (model && idx < model->d->m_items.size()) {
        int i = 0;
        if (!type.isEmpty()) {
            foreach (QDeclarativeOrganizerItem* di, model->d->m_items) {
                if (di->item().type() == type) {
                    if (i == idx) {
                        item = di;
                        break;
                    } else {
                        i++;
                    }
                }
            }
        } else {
            item = model->d->m_items.at(idx);
        }
    }
    return item;
}

void  QDeclarativeOrganizerModel::item_clear(QDeclarativeListProperty<QDeclarativeOrganizerItem> *p)
{
    QString type((const char*)(p->data));
    QDeclarativeOrganizerModel* model = qobject_cast<QDeclarativeOrganizerModel*>(p->object);

    if (model) {
        if (!type.isEmpty()) {
            foreach (QDeclarativeOrganizerItem* di, model->d->m_items) {
                if (di->item().type() == type) {
                    di->deleteLater();
                    model->d->m_items.removeAll(di);
                }
            }
        } else {
            model->d->m_items.clear();
        }
        emit model->modelChanged();
    }
}

void QDeclarativeOrganizerModel::sortOrder_append(QDeclarativeListProperty<QDeclarativeOrganizerItemSortOrder> *p, QDeclarativeOrganizerItemSortOrder *sortOrder)
{
    QDeclarativeOrganizerModel* model = qobject_cast<QDeclarativeOrganizerModel*>(p->object);
    if (model && sortOrder) {
        QObject::connect(sortOrder, SIGNAL(sortOrderChanged()), model, SIGNAL(sortOrdersChanged()));
        model->d->m_declarativeSortOrders.append(sortOrder);
        model->d->m_sortOrders.append(sortOrder->sortOrder());
        emit model->sortOrdersChanged();
    }
}

int  QDeclarativeOrganizerModel::sortOrder_count(QDeclarativeListProperty<QDeclarativeOrganizerItemSortOrder> *p)
{
    QDeclarativeOrganizerModel* model = qobject_cast<QDeclarativeOrganizerModel*>(p->object);
    if (model)
        return model->d->m_declarativeSortOrders.size();
    return 0;
}
QDeclarativeOrganizerItemSortOrder * QDeclarativeOrganizerModel::sortOrder_at(QDeclarativeListProperty<QDeclarativeOrganizerItemSortOrder> *p, int idx)
{
    QDeclarativeOrganizerModel* model = qobject_cast<QDeclarativeOrganizerModel*>(p->object);

    QDeclarativeOrganizerItemSortOrder* sortOrder = 0;
    if (model) {
        int i = 0;
        foreach (QDeclarativeOrganizerItemSortOrder* s, model->d->m_declarativeSortOrders) {
            if (i == idx) {
                sortOrder = s;
                break;
            } else {
                i++;
            }
        }
    }
    return sortOrder;
}
void  QDeclarativeOrganizerModel::sortOrder_clear(QDeclarativeListProperty<QDeclarativeOrganizerItemSortOrder> *p)
{
    QDeclarativeOrganizerModel* model = qobject_cast<QDeclarativeOrganizerModel*>(p->object);

    if (model) {
        model->d->m_sortOrders.clear();
        model->d->m_declarativeSortOrders.clear();
        emit model->sortOrdersChanged();
    }
}