summaryrefslogtreecommitdiffstats
path: root/src/imports/contacts/qdeclarativecontactmodel.cpp
blob: f8677510f52815c19162b33a9fc6c439b5d515e1 (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
/****************************************************************************
**
** Copyright (C) 2017 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the QtQml module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qdeclarativecontactmodel_p.h"

#include <QtCore/qfile.h>
#include <QtCore/qhash.h>
#include <QtCore/qmap.h>
#include <QtCore/qpointer.h>
#include <QtCore/qurl.h>
#include <QtCore/qmimedatabase.h>
#include <QtCore/qmimetype.h>
#include <QtCore/qtemporaryfile.h>
#include <QtCore/qdir.h>

#include <QtGui/qcolor.h>
#include <QtGui/qpixmap.h>

#include <QtQml/qqmlinfo.h>
#include <QtQml/qqmlengine.h>

#include <QtContacts/qcontactdetails.h>
#include <QtContacts/qcontactmanager.h>
#include <QtContacts/qcontactmanagerengine.h>
#include <QtContacts/qcontactdetailfilter.h>
#include <QtContacts/qcontactidfilter.h>
#include <QtContacts/qcontactintersectionfilter.h>
#include <QtContacts/qcontactrequests.h>

#include <QtVersit/qversitreader.h>
#include <QtVersit/qversitwriter.h>
#include <QtVersit/qversitcontactimporter.h>
#include <QtVersit/qversitcontactexporter.h>

QTCONTACTS_USE_NAMESPACE
QTVERSIT_USE_NAMESPACE

QT_BEGIN_NAMESPACE

/*!
    \qmltype ContactModel
    \instantiates QDeclarativeContactModel
    \brief The ContactModel element provides access to contacts from the contacts store.
    \ingroup qml-contacts-main
    \inqmlmodule QtContacts

    This element is part of the \b{QtContacts} module.

    ContactModel provides a model of contacts from the contacts 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 contacts changes, can be
    controlled with \l ContactModel::autoUpdate property.

    There are two ways of accessing the contact data: via model by using views and delegates,
    or alternatively via \l contacts 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 ContactModel are display, decoration and \c contact.
    Through the \c contact role can access any data provided by the Contact element.

    \sa RelationshipModel, Contact, {QContactManager}
*/

// Helper class to store contact binary data into a temporary file
//
// QContactVcard only supports URL values for images. During a vcard import if the contact cotains
// an avatar, ringtone or any property formated in a binary data, QVersit will use the
// ContactExporterResourceHandler to store the binary data.
// The default implementation of QVersitResourceHandler does not store any data and that
// causes avatar data loss during the import process.
// This class will store the data into a temporary file and removes the file when the model gets destroyed.
class ContactExporterResourceHandler : public QVersitResourceHandler
{
public:
    ContactExporterResourceHandler()
    {
    }

    ~ContactExporterResourceHandler()
    {
        foreach (const QString& fileName, m_files)
            QFile::remove(fileName);

        m_files.clear();
    }

    bool saveResource(const QByteArray& contents,
                      const QVersitProperty& property,
                      QString* location)
    {
        const QMimeType mt = QMimeDatabase().mimeTypeForData(contents);
        QString extension(QStringLiteral("data"));
        if (mt.isValid())
            extension = mt.suffixes()[0];

        // use property.name() to create a new file for each binary property (avatar, ringtone, etc...)
        QTemporaryFile tmpFile(QString::fromLatin1("%1/%2_XXXXXX.%3")
                               .arg(QDir::tempPath())
                               .arg(property.name().toLower())
                               .arg(extension));
        tmpFile.setAutoRemove(false);
        if (tmpFile.open()) {
            // the location expect a string in url format ex: file:///tmp/filename.png
            *location = QUrl::fromLocalFile(tmpFile.fileName()).toString();
            m_files << *location;
            tmpFile.write(contents);
            tmpFile.close();
            return true;
        }
        return false;
    }

    bool loadResource(const QString &location, QByteArray *contents, QString *mimeType)
    {
        if (location.isEmpty())
            return false;

        QFile file(location);
        if (!file.open(QIODevice::ReadOnly))
            return false;

        *contents = file.readAll();
        const QMimeType mt = QMimeDatabase().mimeTypeForData(*contents);
        if (mt.isValid())
            *mimeType = mt.suffixes()[0];

        return !contents->isEmpty();
    }

    QStringList m_files;
};


class QDeclarativeContactModelPrivate
{
public:
    QDeclarativeContactModelPrivate()
        :m_manager(0),
        m_fetchHint(0),
        m_filter(0),
        m_error(QContactManager::NoError),
        m_autoUpdate(true),
        m_componentCompleted(false),
        m_progressiveLoading(true),
        m_updatePendingFlag(QDeclarativeContactModelPrivate::NonePending)
    {
    }
    ~QDeclarativeContactModelPrivate()
    {
        if (m_manager)
            delete m_manager;
    }

    enum UpdateTypePending {
        NonePending = 0x0,
        UpdatingContactsPending = 0x1,
        UpdatingCollectionsPending = 0x2
    };

    QList<QDeclarativeContact*> m_contacts;
    QMap<QContactId, QDeclarativeContact*> m_contactMap;
    QMap<QContactId, QDeclarativeContact*> m_contactFetchedMap;
    QContactManager* m_manager;
    QDeclarativeContactFetchHint* m_fetchHint;
    QList<QDeclarativeContactSortOrder*> m_sortOrders;
    QDeclarativeContactFilter* m_filter;

    QVersitReader m_reader;
    QVersitWriter m_writer;
    QStringList m_importProfiles;
    ContactExporterResourceHandler m_resourceHandler;

    QContactManager::Error m_error;

    bool m_autoUpdate;
    bool m_componentCompleted;
    QUrl m_lastExportUrl;
    QUrl m_lastImportUrl;
    QAtomicInt m_lastRequestId;
    QHash<QContactAbstractRequest *, int> m_requestIdHash;
    QList<QContactFetchRequest*> m_pendingRequests;
    QList<QContact> m_pendingContacts;
    QList<QDeclarativeContactCollection*> m_collections;
    bool m_progressiveLoading;
    int m_updatePendingFlag;
};

QDeclarativeContactModel::QDeclarativeContactModel(QObject *parent) :
    QAbstractListModel(parent),
    d(new QDeclarativeContactModelPrivate)
{
    connect(this, SIGNAL(managerChanged()), SLOT(doUpdate()));
    connect(this, SIGNAL(filterChanged()), SLOT(doContactUpdate()));
    connect(this, SIGNAL(fetchHintChanged()), SLOT(doContactUpdate()));
    connect(this, SIGNAL(sortOrdersChanged()), SLOT(doContactUpdate()));

    //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(contactsExported(QVersitWriter::State)));
}

QDeclarativeContactModel::~QDeclarativeContactModel()
{
}

QHash<int, QByteArray> QDeclarativeContactModel::roleNames() const
{
    QHash<int, QByteArray> roleNames = QAbstractItemModel::roleNames();
    roleNames.insert(ContactRole, "contact");
    return roleNames;
}

/*!
  \qmlproperty string ContactModel::manager

  This property holds the manager uri of the contact backend engine.
  */
QString QDeclarativeContactModel::manager() const
{
    if (d->m_manager)
        return d->m_manager->managerName();
    return QString();
}
void QDeclarativeContactModel::setManager(const QString& managerName)
{
    if (d->m_manager && (managerName == d->m_manager->managerName() || managerName == d->m_manager->managerUri()))
        return;

    if (d->m_manager) {
        cancelUpdate();
        delete d->m_manager;
    }

    d->m_manager = new QContactManager(managerName);

    connect(d->m_manager, SIGNAL(dataChanged()), this, SLOT(doUpdate()));
    connect(d->m_manager, SIGNAL(contactsAdded(QList<QContactId>)), this, SLOT(onContactsAdded(QList<QContactId>)));
    connect(d->m_manager, SIGNAL(contactsRemoved(QList<QContactId>)), this, SLOT(onContactsRemoved(QList<QContactId>)));
    connect(d->m_manager, SIGNAL(contactsChanged(QList<QContactId>,QList<QContactDetail::DetailType>)), this, SLOT(onContactsChanged(QList<QContactId>)));
    connect(d->m_manager, SIGNAL(collectionsAdded(QList<QContactCollectionId>)), this, SLOT(fetchCollections()));
    connect(d->m_manager, SIGNAL(collectionsChanged(QList<QContactCollectionId>)), this, SLOT(fetchCollections()));
    connect(d->m_manager, SIGNAL(collectionsRemoved(QList<QContactCollectionId>)), this, SLOT(fetchCollections()));


    if (d->m_error != QContactManager::NoError) {
        d->m_error = QContactManager::NoError;
        emit errorChanged();
    }

    emit managerChanged();
}

void QDeclarativeContactModel::componentComplete()
{
    if (!d->m_manager)
        setManager(QString());

    d->m_componentCompleted = true;

    if (d->m_autoUpdate)
        update();
}
/*!
  \qmlproperty bool ContactModel::autoUpdate

  This property indicates whether or not the contact model should be updated automatically, default value is true.
  */
void QDeclarativeContactModel::setAutoUpdate(bool autoUpdate)
{
    if (autoUpdate == d->m_autoUpdate)
        return;
    d->m_autoUpdate = autoUpdate;
    emit autoUpdateChanged();
}

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

void QDeclarativeContactModel::update()
{
    if (!d->m_componentCompleted || d->m_updatePendingFlag)
        return;
    // Disallow possible duplicate request triggering
    d->m_updatePendingFlag = (QDeclarativeContactModelPrivate::UpdatingContactsPending | QDeclarativeContactModelPrivate::UpdatingCollectionsPending);
    QMetaObject::invokeMethod(this, "fetchCollections", Qt::QueuedConnection);
}

/*!
  \qmlmethod ContactModel::updateContacts()

  Manually update the contact model contacts.

  \sa ContactModel::update
  \sa ContactModel::updateCollections
  \sa ContactModel::autoUpdate
  */
void QDeclarativeContactModel::updateContacts()
{
    if (!d->m_componentCompleted || d->m_updatePendingFlag)
        return;
    // Disallow possible duplicate request triggering
    d->m_updatePendingFlag = QDeclarativeContactModelPrivate::UpdatingContactsPending;
    QMetaObject::invokeMethod(this, "fetchAgain", Qt::QueuedConnection);
}

/*!
  \qmlmethod ContactModel::updateCollections()

  Manually update the contact model collections.

  \sa ContactModel::update
  \sa ContactModel::updateContacts
  \sa ContactModel::autoUpdate
  */
void QDeclarativeContactModel::updateCollections()
{
    if (!d->m_componentCompleted || d->m_updatePendingFlag)
        return;
    // Disallow possible duplicate request triggering
    d->m_updatePendingFlag = QDeclarativeContactModelPrivate::UpdatingCollectionsPending;
    QMetaObject::invokeMethod(this, "fetchCollections", Qt::QueuedConnection);
}

/*!
  \qmlmethod ContactModel::cancelUpdate()

  Cancel the running contact model content update request.

  \sa ContactModel::autoUpdate
  \sa ContactModel::update
  */
void QDeclarativeContactModel::cancelUpdate()
{
    foreach (QContactFetchRequest *req, d->m_pendingRequests) {
        req->cancel();
        req->deleteLater();
    }
    d->m_pendingRequests.clear();;
    d->m_updatePendingFlag = QDeclarativeContactModelPrivate::NonePending;
}

void QDeclarativeContactModel::doContactUpdate()
{
    if (d->m_autoUpdate)
        updateContacts();
}

/*!
  \qmlproperty string ContactModel::error

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

  This property is read only.
  */
QString QDeclarativeContactModel::error() const
{
    if (d->m_manager) {
        switch (d->m_error) {
        case QContactManager::DoesNotExistError:
            return QStringLiteral("DoesNotExist");
        case QContactManager::AlreadyExistsError:
            return QStringLiteral("AlreadyExists");
        case QContactManager::InvalidDetailError:
            return QStringLiteral("InvalidDetail");
        case QContactManager::InvalidRelationshipError:
            return QStringLiteral("InvalidRelationship");
        case QContactManager::LockedError:
            return QStringLiteral("LockedError");
        case QContactManager::DetailAccessError:
            return QStringLiteral("DetailAccessError");
        case QContactManager::PermissionsError:
            return QStringLiteral("PermissionsError");
        case QContactManager::OutOfMemoryError:
            return QStringLiteral("OutOfMemory");
        case QContactManager::NotSupportedError:
            return QStringLiteral("NotSupported");
        case QContactManager::BadArgumentError:
            return QStringLiteral("BadArgument");
        case QContactManager::UnspecifiedError:
            return QStringLiteral("UnspecifiedError");
        case QContactManager::VersionMismatchError:
            return QStringLiteral("VersionMismatch");
        case QContactManager::LimitReachedError:
            return QStringLiteral("LimitReached");
        case QContactManager::InvalidContactTypeError:
            return QStringLiteral("InvalidContactType");
        default:
            break;
        }
    }
    return QStringLiteral("NoError");
}


/*!
  \qmlproperty list<string> ContactModel::availableManagers

  This property holds the list of available manager names.
  This property is read only.
  */
QStringList QDeclarativeContactModel::availableManagers() const
{
    return QContactManager::availableManagers();
}
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();
   }

}

/*!
  \qmlproperty enumeration ContactModel::ImportError

  Defines the errors cases for \l ContactModel::importContacts() -function.

  \list
  \li ContactModel::ImportNoError             Completed successfully, no error.
  \li ContactModel::ImportUnspecifiedError    Unspecified error.
  \li ContactModel::ImportIOError             Input/output error.
  \li ContactModel::ImportOutOfMemoryError    Out of memory error.
  \li ContactModel::ImportNotReadyError       Not ready for importing. Only one import operation can be active at a time.
  \li ContactModel::ImportParseError          Error during parsing.
  \endlist
*/

/*!
  \qmlsignal ContactModel::onImportCompleted(ImportError error, URL url, list<string> ids)

  This signal is emitted, when \l ContactModel::importContacts() completes. The success of operation
  can be seen on \a error which is defined in \l ContactModel::ImportError. \a url indicates the
  file, which was imported. \a ids contains the imported contacts ids.

  If the operation was successful, contacts are now imported to backend. If \l ContactModel::autoUpdate
  is enabled, \l ContactModel::modelChanged will be emitted when imported contacts are also visible on
  \l ContactModel's data model.

  \sa ContactModel::importContacts
 */

/*!
  \qmlmethod void ContactModel::importContacts(url url, list<string> profiles)

  Import contacts from a vcard by the given \a url and optional \a profiles.
  Only one import operation can be active at a time.
  Supported profiles are:
  \list
  \li "Sync"  Imports contacts in sync mode, currently, this is the same as passing in an empty list, and is generally what you want.
  \li "Backup" imports contacts in backup mode, use this mode if the vCard was generated by exporting in backup mode.

  \endlist

  \sa QVersitContactHandlerFactory
  \sa QVersitContactHandlerFactory::ProfileSync()
  \sa QVersitContactHandlerFactory::ProfileBackup()

  */
void QDeclarativeContactModel::importContacts(const QUrl& url, const QStringList& profiles)
{
    // Reader is capable of handling only one request at the time.
    ImportError importError = ImportNotReadyError;
    if (d->m_reader.state() != QVersitReader::ActiveState) {

        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);
            if (d->m_reader.startReading()) {
                d->m_lastImportUrl = url;
                return;
            }
            importError = QDeclarativeContactModel::ImportError(d->m_reader.error());
        } else {
            importError = ImportIOError;
        }
    }
    emit importCompleted(importError, url, QStringList());
}

/*!
  \qmlmethod void ContactModel::exportContacts(url url, list<string> profiles, list<variant> declarativeContacts)

  Export all contacts of this model into a vcard file to the given \a url by optional \a profiles.
  The optional \a declarativeContacts list can be used to export an arbitrary list of QDeclarativeContact objects
  not necessarily belonging to the data set of this model.
  At the moment only the local file url is supported in export method.
  Also, only one export operation can be active at a time.
  Supported profiles are:
  \list
  \li "Sync"  exports contacts in sync mode, currently, this is the same as passing in an empty list, and is generally what you want.
  \li "Backup" exports contacts in backup mode, this will add non-standard properties to the generated vCard
              to try to save every detail of the contacts. Only use this if the vCard is going to be imported using the backup profile.
#include "moc_qdeclarativecontactmodel_p.cpp"
  \endlist

  \sa QVersitContactHandlerFactory
  \sa QVersitContactHandlerFactory::ProfileSync()
  \sa QVersitContactHandlerFactory::ProfileBackup()
  */
void QDeclarativeContactModel::exportContacts(const QUrl& url, const QStringList& profiles, const QVariantList &declarativeContacts)
{
    // Writer is capable of handling only one request at the time.
    ExportError exportError = ExportNotReadyError;
    if (d->m_writer.state() != QVersitWriter::ActiveState) {
        QString profile = profiles.isEmpty()? QString() : profiles.at(0);
        //only one profile string supported now.
        QVersitContactExporter exporter(profile);
        exporter.setResourceHandler(&d->m_resourceHandler);

        QList<QContact> contacts;
        if (declarativeContacts.isEmpty()) {
            foreach (QDeclarativeContact* dc, d->m_contacts) {
                contacts.append(dc->contact());
            }

        } else {
            foreach (const QVariant &contactVariant, declarativeContacts) {
                QObject *rawObject = contactVariant.value<QObject*>();
                QDeclarativeContact *dc = qobject_cast<QDeclarativeContact*>(rawObject);
                if (dc) {
                    contacts.append(dc->contact());
                }
            }
        }

        exporter.exportContacts(contacts, QVersitDocument::VCard30Type);
        QList<QVersitDocument> documents = exporter.documents();
        QFile* file = new QFile(urlToLocalFileName(url));
        bool ok = file->open(QIODevice::WriteOnly);
        if (ok) {
            d->m_writer.setDevice(file);
            if (d->m_writer.startWriting(documents)) {
                d->m_lastExportUrl = url;
                return;
            }
            exportError = QDeclarativeContactModel::ExportError(d->m_writer.error());
        } else {
            exportError = ExportIOError;
        }
    }
    emit exportCompleted(exportError, url);
}

void QDeclarativeContactModel::contactsExported(QVersitWriter::State state)
{
    if (state == QVersitWriter::FinishedState || state == QVersitWriter::CanceledState) {
         delete d->m_writer.device();
         d->m_writer.setDevice(0);
         emit exportCompleted(QDeclarativeContactModel::ExportError(d->m_writer.error()), d->m_lastExportUrl);
    }
}

void QDeclarativeContactModel::onFetchedContactDestroyed(QObject *obj)
{
    QContactId id = d->m_contactFetchedMap.key(static_cast<QDeclarativeContact*>(obj));
    if (!id.isNull())
        d->m_contactFetchedMap.remove(id);
}

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



/*!
  \qmlproperty Filter ContactModel::filter

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

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

void QDeclarativeContactModel::setFilter(QDeclarativeContactFilter* filter)
{
    if (d->m_filter != filter) {
        if (d->m_filter)
            disconnect(d->m_filter, SIGNAL(filterChanged()), this, SIGNAL(filterChanged()));
        d->m_filter = filter;
        if (d->m_filter)
            connect(d->m_filter, SIGNAL(filterChanged()), SIGNAL(filterChanged()), Qt::UniqueConnection);
        emit filterChanged();
    }
}

/*!
  \qmlproperty FetchHint ContactModel::fetchHint

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

  \sa FetchHint
  */
QDeclarativeContactFetchHint* QDeclarativeContactModel::fetchHint() const
{
    return d->m_fetchHint;
}
void QDeclarativeContactModel::setFetchHint(QDeclarativeContactFetchHint* fetchHint)
{
    if (d->m_fetchHint != fetchHint) {
        if (d->m_fetchHint)
            disconnect(d->m_fetchHint, SIGNAL(fetchHintChanged()), this, SIGNAL(fetchHintChanged()));
        d->m_fetchHint = fetchHint;
        if (d->m_fetchHint)
            connect(d->m_fetchHint, SIGNAL(fetchHintChanged()), SIGNAL(fetchHintChanged()), Qt::UniqueConnection);
        emit fetchHintChanged();
    }
}

/*!
  \qmlproperty list<Contact> ContactModel::contacts

  This property holds the list of contacts.

  \sa Contact
  */
QQmlListProperty<QDeclarativeContact> QDeclarativeContactModel::contacts()
{
    return { this,
             nullptr,
             &contacts_append,
             &contacts_count,
             &contacts_at,
             &contacts_clear };
}



void QDeclarativeContactModel::contacts_append(QQmlListProperty<QDeclarativeContact>* prop, QDeclarativeContact* contact)
{
    Q_UNUSED(prop);
    Q_UNUSED(contact);
    qWarning() << Q_FUNC_INFO << "appending contacts is not currently supported";
}

qsizetype QDeclarativeContactModel::contacts_count(QQmlListProperty<QDeclarativeContact>* prop)
{
    return static_cast<QDeclarativeContactModel*>(prop->object)->d->m_contacts.count();
}

QDeclarativeContact* QDeclarativeContactModel::contacts_at(QQmlListProperty<QDeclarativeContact>* prop, qsizetype index)
{
    return static_cast<QDeclarativeContactModel*>(prop->object)->d->m_contacts.at(index);
}

void QDeclarativeContactModel::contacts_clear(QQmlListProperty<QDeclarativeContact>* prop)
{
    QDeclarativeContactModel* model = static_cast<QDeclarativeContactModel*>(prop->object);
    model->clearContacts();
    emit model->contactsChanged();
}


/*!
  \qmlproperty list<SortOrder> ContactModel::sortOrders

  This property holds a list of sort orders used by the contacts model.
  \sa SortOrder
  */
QQmlListProperty<QDeclarativeContactSortOrder> QDeclarativeContactModel::sortOrders()
{
    return { this,
             nullptr,
             &sortOrder_append,
             &sortOrder_count,
             &sortOrder_at,
             &sortOrder_clear };
}

void QDeclarativeContactModel::startImport(QVersitReader::State state)
{
    if (state == QVersitReader::FinishedState || state == QVersitReader::CanceledState) {
        QVersitContactImporter importer(d->m_importProfiles);
        importer.setResourceHandler(&d->m_resourceHandler);
        importer.importDocuments(d->m_reader.results());
        QList<QContact> contacts = importer.contacts();

        delete d->m_reader.device();
        d->m_reader.setDevice(0);

        QStringList ids;

        if (d->m_manager) {
            if (!d->m_manager->saveContacts(&contacts)) {
                if (d->m_error != d->m_manager->error()) {
                    d->m_error = d->m_manager->error();
                    emit errorChanged();
                }
            } else {
                foreach (const QContact &c, contacts) {
                    ids << c.id().toString();
                }
            }
        }

        emit importCompleted(QDeclarativeContactModel::ImportError(d->m_reader.error()), d->m_lastImportUrl, ids);
    }
}

/*!
  \qmlsignal ContactModel::contactsFetched(int requestId, list<Contact> fetchedContacts)

  This signal is emitted, when a contact fetch request is finished.

  \sa ContactModel::fetchContacts
 */

/*!
    \qmlmethod int ContactModel::fetchContacts(list<string> contactIds)

    Starts a request to fetch contacts by the given \a contactIds, and returns the unique ID of this request.
    -1 is returned if the request can't be started.

    Note that the contacts fetched won't be added to the model, but can be accessed through the contactsFetched
    signal handler.

    \sa ContactModel::contactsFetched
  */
int QDeclarativeContactModel::fetchContacts(const QStringList &contactIds)
{
    if (contactIds.isEmpty())
        return -1;

    QContactFetchByIdRequest *fetchRequest = new QContactFetchByIdRequest(this);
    connect(fetchRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)),
            this, SLOT(onFetchContactsRequestStateChanged(QContactAbstractRequest::State)));
    fetchRequest->setManager(d->m_manager);

    QList<QContactId> ids;
    foreach (const QString &contactId, contactIds)
        ids.append(QContactId::fromString(contactId));
    fetchRequest->setIds(ids);
    int requestId = d->m_lastRequestId.fetchAndAddOrdered(1);
    d->m_requestIdHash.insert(fetchRequest, requestId);
    if (fetchRequest->start()) {
        return requestId;
    } else {
        d->m_requestIdHash.remove(fetchRequest);
        return -1;
    }
}

/*!
  \qmlmethod ContactModel::removeCollection(string collectionId)
  Removes asynchronously the contact collection with the given \a collectionId from the backend.
  */
void QDeclarativeContactModel::removeCollection(const QString &collectionId)
{
    QContactCollectionRemoveRequest* req = new QContactCollectionRemoveRequest(this);
    req->setManager(d->m_manager);
    req->setCollectionId(QContactCollectionId::fromString(collectionId));

    connect(req, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(onRequestStateChanged(QContactAbstractRequest::State)));

    req->start();
}

/*!
  \qmlmethod OContactModel::saveCollection(Collection collection)

  Saves asynchronously the given \a collection into the contact backend.
 */
void QDeclarativeContactModel::saveCollection(QDeclarativeContactCollection *declColl)
{
    if (declColl) {
        QContactCollection collection = declColl->collection();
        QContactCollectionSaveRequest* req = new QContactCollectionSaveRequest(this);
        req->setManager(d->m_manager);
        req->setCollection(collection);

        if (declColl->collection().id().isNull()) {
            // if the collection id is empty this means that this is a new collection
            // we need to keep trace of this declarative collection to update with the
            // new Id as soon as this request finish
            QPointer<QDeclarativeContactCollection> pCollection = declColl;
            req->setProperty("DeclarativeCollection", QVariant::fromValue(pCollection));
        }

        connect(req, SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(onRequestStateChanged(QContactAbstractRequest::State)));
        req->start();
    }
}

/*!
  \qmlmethod OContactModel::fetchCollections()
  Fetch asynchronously a list of contact collections from the contact backend.
*/
void QDeclarativeContactModel::fetchCollections()
{
    // fetchCollections() is used for both direct calls and
    // signals from model. For signal from model, check also the
    // autoupdate-flag.
    if (sender() == d->m_manager && !d->m_autoUpdate) {
        return;
    }

    QContactCollectionFetchRequest* req = new QContactCollectionFetchRequest(this);
    connect(req,SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(collectionsFetched()));
    req->setManager(d->m_manager);
    req->start();
}

/*!
    \internal
 */
void QDeclarativeContactModel::onFetchContactsRequestStateChanged(QContactAbstractRequest::State state)
{
    if (state != QContactAbstractRequest::FinishedState)
        return;

    QContactFetchByIdRequest *request = qobject_cast<QContactFetchByIdRequest *>(sender());
    Q_ASSERT(request);

    checkError(request);

    const int requestId = d->m_requestIdHash.value(request, -1);
    if (requestId == -1)
        qWarning() << Q_FUNC_INFO << "transaction not found from the request hash";
    else
        d->m_requestIdHash.remove(request);
    QVariantList list;
    if (request->error() == QContactManager::NoError) {
        QList<QContact> contacts(request->contacts());
        foreach (const QContact &contact, contacts) {
            // if the contact was already fetched update the contact
            QDeclarativeContact *declarativeContact = d->m_contactFetchedMap.value(contact.id(), 0);
            if (!declarativeContact) {
                declarativeContact = new QDeclarativeContact(this);
                // Transfer the ownership to QML
                // The model will destroy the contact if it get removed from the backend, otherwise the QML side need to destroy it.
                QQmlEngine::setObjectOwnership(declarativeContact, QQmlEngine::JavaScriptOwnership);

                // keep track of contact destruction to remove it from the list if QML destroys it
                connect(declarativeContact, SIGNAL(destroyed(QObject*)), SLOT(onFetchedContactDestroyed(QObject*)));

                // we need keep track of the contact to update it if the contact get update on the backend. or destroy it
                // if the contact get removed from the backend
                d->m_contactFetchedMap[contact.id()] = declarativeContact;
            }
            declarativeContact->setContact(contact);
            list.append(QVariant::fromValue(declarativeContact));
        }
    }
    emit contactsFetched(requestId, list);
    request->deleteLater();
}

/*!
    \internal
 */
void QDeclarativeContactModel::collectionsFetched()
{
    QContactCollectionFetchRequest* req = qobject_cast<QContactCollectionFetchRequest*>(QObject::sender());
    Q_ASSERT(req);
    if (req->isFinished() && QContactManager::NoError == req->error()) {
        d->m_updatePendingFlag &= ~QDeclarativeContactModelPrivate::UpdatingCollectionsPending;
        // prepare tables
        QHash<QString, const QContactCollection*> collections;
        foreach (const QContactCollection& collection, req->collections()) {
            collections.insert(collection.id().toString(), &collection);
        }
        QHash<QString, QDeclarativeContactCollection*> declCollections;
        foreach (QDeclarativeContactCollection* declCollection, d->m_collections) {
            declCollections.insert(declCollection->collection().id().toString(), declCollection);
        }
        // go tables through
        for (auto it = collections.cbegin(), end = collections.cend(); it != end; ++it) {
            if (declCollections.contains(it.key())) {
                // collection on both sides, update the declarative collection
                declCollections.value(it.key())->setCollection(*it.value());
            } else {
                // new collection, add it to declarative collection list
                QDeclarativeContactCollection* declCollection = new QDeclarativeContactCollection(this);
                declCollection->setCollection(*it.value());
                d->m_collections.append(declCollection);
            }
        }
        for (auto it = declCollections.cbegin(), end = declCollections.cend(); it != end; ++it) {
            if (!collections.contains(it.key())) {
                // collection deleted on the backend side, delete from declarative collection list
                QDeclarativeContactCollection* toBeDeletedColl = it.value();
                d->m_collections.removeOne(toBeDeletedColl);
                toBeDeletedColl->deleteLater();
            }
        }
        emit collectionsChanged();
        if (d->m_updatePendingFlag & QDeclarativeContactModelPrivate::UpdatingContactsPending)
            QMetaObject::invokeMethod(this, "fetchAgain", Qt::QueuedConnection);
        req->deleteLater();
    }
    checkError(req);
}

void QDeclarativeContactModel::clearContacts()
{
    qDeleteAll(d->m_contacts);
    d->m_contacts.clear();
    d->m_contactMap.clear();
    qDeleteAll(d->m_contactFetchedMap.values());
    d->m_contactFetchedMap.clear();
}

void QDeclarativeContactModel::fetchAgain()
{
    QList<QContactSortOrder> sortOrders;
    foreach (QDeclarativeContactSortOrder* so, d->m_sortOrders) {
        sortOrders.append(so->sortOrder());
    }
    QContactFetchRequest* fetchRequest = new QContactFetchRequest(this);

    fetchRequest->setManager(d->m_manager);
    fetchRequest->setSorting(sortOrders);

    if (d->m_filter){
        fetchRequest->setFilter(d->m_filter->filter());
    } else {
        fetchRequest->setFilter(QContactFilter());
    }

    fetchRequest->setFetchHint(d->m_fetchHint ? d->m_fetchHint->fetchHint() : QContactFetchHint());

    connect(fetchRequest, SIGNAL(resultsAvailable()), this, SLOT(requestUpdated()));
    connect(fetchRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)),
            this, SLOT(fetchRequestStateChanged(QContactAbstractRequest::State)));

    // cancel all previous requests
    foreach (QContactFetchRequest *req, d->m_pendingRequests) {
        req->cancel();
        req->deleteLater();
    }

    d->m_pendingContacts.clear();
    d->m_pendingRequests.clear();
    d->m_pendingRequests.append(fetchRequest);

    // if we have no contacts yet, we can display results as soon as they arrive
    // but if we are updating the model after a sort or filter change, we have to
    // wait for all contacts before processing the update
    d->m_progressiveLoading = d->m_contacts.isEmpty();

    fetchRequest->start();
}

void QDeclarativeContactModel::requestUpdated()
{

    QContactFetchRequest* req = qobject_cast<QContactFetchRequest*>(QObject::sender());
    Q_ASSERT(req);
    if (req) {
        QList<QContact> contacts = req->contacts();

        // if we are starting from scratch, we can show contact results as they arrive
        if (d->m_progressiveLoading) {
            QList<QDeclarativeContact*> dcs;
            foreach (const QContact &c, contacts) {
                if (d->m_contactMap.contains(c.id())) {
                    QDeclarativeContact* dc = d->m_contactMap.value(c.id());
                    dc->setContact(c);
                } else {
                    QDeclarativeContact* dc = new QDeclarativeContact(this);
                    if (dc) {
                        d->m_contactMap.insert(c.id(), dc);
                        dc->setContact(c);
                        dcs.append(dc);
                    }
                }
            }

            if (dcs.count() > 0) {
                beginInsertRows(QModelIndex(), d->m_contacts.count(), d->m_contacts.count() + dcs.count() - 1);
                // At this point we need to relay on the backend and assume that the partial results are following the fetch sorting property
                d->m_contacts += dcs;
                endInsertRows();

                emit contactsChanged();
            }
        } else {
            d->m_pendingContacts << contacts;
        }

        checkError(req);
    }
}

void QDeclarativeContactModel::fetchRequestStateChanged(QContactAbstractRequest::State newState)
{
    if (newState != QContactAbstractRequest::FinishedState)
        return;

    d->m_updatePendingFlag &= ~QDeclarativeContactModelPrivate::UpdatingContactsPending;
    QContactFetchRequest* req = qobject_cast<QContactFetchRequest*>(QObject::sender());
    Q_ASSERT(req);
    if (req) {
        // if we were not processing contacts as soon as they arrive, we need to process them here.
        if (!d->m_progressiveLoading) {
            // start by removing the contacts that don't belong to this result set anymore
            for (int i = d->m_contacts.count()-1; i >= 0; --i) {
                QDeclarativeContact *contact = d->m_contacts[i];
                if (!d->m_pendingContacts.contains(contact->contact())) {
                    beginRemoveRows(QModelIndex(), i, i);
                    d->m_contacts.removeAt(i);
                    d->m_contactMap.remove(contact->contact().id());
                    endRemoveRows();
                }
            }

            // now insert new contacts and move existing ones to their final positions
            int count = d->m_pendingContacts.count();
            for (int i = 0; i < count; ++i) {
                QContact c = d->m_pendingContacts[i];
                if (!d->m_contactMap.contains(c.id())) {
                    QDeclarativeContact* dc = new QDeclarativeContact(this);
                    dc->setContact(c);
                    beginInsertRows(QModelIndex(), i, i);
                    d->m_contacts.insert(i, dc);
                    d->m_contactMap.insert(c.id(),dc);
                    endInsertRows();
                } else {
                    QDeclarativeContact *contact = d->m_contactMap[c.id()];

                    // If there are duplicates in the pending contacts list, then the current index
                    // can be outside this contact lists range and we need to adjust it to avoid crashing.
                    const int oldIdx = d->m_contacts.indexOf(contact);
                    const int newIdx = i < d->m_contacts.size() ? i : d->m_contacts.size() - 1;
                    if (oldIdx != newIdx) {
                        beginMoveRows(QModelIndex(), oldIdx, oldIdx, QModelIndex(), newIdx);
                        d->m_contacts.move(oldIdx, newIdx);
                        endMoveRows();
                    }
                }
            }
            emit contactsChanged();
        }

        // and now clear the pending contact list as the model is up-to-date
        d->m_pendingContacts.clear();
        d->m_pendingRequests.removeOne(req);
        req->deleteLater();
    }
}

/*!
    \internal
 */
void QDeclarativeContactModel::doUpdate()
{
    if (d->m_autoUpdate)
        update();
}

/*!
  \qmlmethod ContactModel::saveContact(Contact contact)

  Save the given \a contact into the contacts backend.
  Once saved successfully, the dirty flags of this contact will be reset.

  \sa Contact::modified
  */
void QDeclarativeContactModel::saveContact(QDeclarativeContact* dc)
{
    if (dc) {
        QContactSaveRequest* req = new QContactSaveRequest(this);
        req->setManager(d->m_manager);
        req->setContact(dc->contact());
        if (dc->contact().id().isNull()) {
            // if the contact id is empty this means that this contact is a new contact
            // we need to keep trace of this declarative contact to update with the
            // new Id as soon as this request finish
            QPointer<QDeclarativeContact> pContact = dc;
            req->setProperty("DeclarativeContact", QVariant::fromValue(pContact));
        }

        connect(req,SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(onRequestStateChanged(QContactAbstractRequest::State)));
        req->start();
    }
}

void QDeclarativeContactModel::onRequestStateChanged(QContactAbstractRequest::State newState)
{
    if (newState != QContactAbstractRequest::FinishedState) {
        return;
    }

    QContactAbstractRequest *request = qobject_cast<QContactAbstractRequest *>(sender());
    Q_ASSERT(request);

    if (request->error() == QContactManager::NoError) {
        switch (request->type()) {
        case QContactAbstractRequest::ContactSaveRequest:
        {
            QVariant vContact = request->property("DeclarativeContact");
            if (vContact.isValid()) {
                QPointer<QDeclarativeContact> pContact = vContact.value<QPointer<QDeclarativeContact> >();
                // Update contact info.
                // this is necessary to make sure that the declarative contact get the new contact ID otherwise
                // the contact Id will be empty
                QList<QContact> contacts = qobject_cast<QContactSaveRequest*>(request)->contacts();
                if (pContact && contacts.length() == 1) {
                    pContact->setContact(contacts[0]);
                }
            }
            break;
        }
        case QContactAbstractRequest::CollectionSaveRequest:
        {
            QVariant vCollection = request->property("DeclarativeCollection");
            if (vCollection.isValid()) {
                QPointer<QDeclarativeContactCollection> pCollection = vCollection.value<QPointer<QDeclarativeContactCollection> >();
                // Update collection info.
                // this is necessary to make sure that the declarative collection get the new collection ID otherwise
                // the collection Id will be empty
                QList<QContactCollection> collections = qobject_cast<QContactCollectionSaveRequest*>(request)->collections();
                if (pCollection && collections.length() == 1) {
                    pCollection->setCollection(collections[0]);
                }
            }
            break;
        }
        default:
            break;
        }
    }
    checkError(request);
    request->deleteLater();
}

void QDeclarativeContactModel::checkError(const QContactAbstractRequest *request)
{
    if (request) {
        updateError(request->error());
    }
}

void QDeclarativeContactModel::updateError(QContactManager::Error error)
{
    if (d->m_error != error) {
        d->m_error = error;
        emit errorChanged();
    }
}

void QDeclarativeContactModel::onContactsAdded(const QList<QContactId>& ids)
{
    if (d->m_autoUpdate && !ids.isEmpty()) {
        QContactFetchRequest *fetchRequest = createContactFetchRequest(ids);
        connect(fetchRequest,SIGNAL(stateChanged(QContactAbstractRequest::State)),
                this, SLOT(onContactsAddedFetchRequestStateChanged(QContactAbstractRequest::State)));
        fetchRequest->start();
    }
}

/*!
  \qmlmethod ContactModel::removeContact(string contactId)
  Remove the contact from the contacts store by given \a contactId.
  After removing a contact it is not possible to save it again.
  \sa Contact::contactId
  */
void QDeclarativeContactModel::removeContact(QString id)
{
    QList<QString> ids;
    ids << id;
    removeContacts(ids);
}

/*!
  \qmlmethod ContactModel::removeContacts(list<string> contactIds)
  Remove the list of contacts from the contacts store by given \a contactIds.
  \sa Contact::contactId
  */

void QDeclarativeContactModel::removeContacts(const QStringList &ids)
{
    QContactRemoveRequest* req = new QContactRemoveRequest(this);
    QList<QContactId> contactIdsAsList;
    req->setManager(d->m_manager);

    foreach (const QString& id, ids) {
        QContactId contactId = QContactId::fromString(id);
        if (!contactId.isNull())
            contactIdsAsList.append(contactId);
    }
    req->setContactIds(contactIdsAsList);

    connect(req,SIGNAL(stateChanged(QContactAbstractRequest::State)), this, SLOT(onRequestStateChanged(QContactAbstractRequest::State)));

    req->start();
}


void QDeclarativeContactModel::onContactsRemoved(const QList<QContactId> &ids)
{
    if (!d->m_autoUpdate)
        return;

    bool emitSignal = false;
    foreach (const QContactId &id, ids) {
        // delete the contact from fetched map if necessary
        QDeclarativeContact* contact = d->m_contactFetchedMap.take(id);
        if (contact)
            contact->deleteLater();

        if (d->m_contactMap.contains(id)) {
            int row = 0;
            //TODO:need a fast lookup
            for (; row < d->m_contacts.count(); row++) {
                if (d->m_contacts.at(row)->contactId() == id.toString())
                    break;
            }

            if (row < d->m_contacts.count()) {
                beginRemoveRows(QModelIndex(), row, row);
                contact = d->m_contacts.takeAt(row);
                contact->deleteLater();
                d->m_contactMap.remove(id);
                endRemoveRows();
                emitSignal = true;
            }
        }
    }
    if (emitSignal)
        emit contactsChanged();
}

void QDeclarativeContactModel::onContactsChanged(const QList<QContactId> &ids)
{
    if (d->m_autoUpdate && !ids.isEmpty()) {
        QContactFetchRequest *fetchRequest = createContactFetchRequest(ids);
        connect(fetchRequest, SIGNAL(stateChanged(QContactAbstractRequest::State)),
                this, SLOT(onContactsChangedFetchRequestStateChanged(QContactAbstractRequest::State)));
        fetchRequest->start();
    }

    // If any contact in the fetchedList has changed we need to update it.
    // We need a different query because feched contacts could not be part of the model.
    //
    // For example: if the model contains a filter
    if (!ids.isEmpty()) {
        QStringList pendingFetch;
        foreach (const QContactId &id, ids) {
            QDeclarativeContact* dc = d->m_contactFetchedMap.value(id);
            if (dc)
                pendingFetch << dc->contactId();
        }
        if (!pendingFetch.isEmpty())
            fetchContacts(pendingFetch);
    }
}

QContactFetchRequest *QDeclarativeContactModel::createContactFetchRequest(const QList<QContactId> &ids)
{
    QContactFetchRequest *fetchRequest = new QContactFetchRequest(this);
    fetchRequest->setManager(d->m_manager);
    fetchRequest->setFetchHint(d->m_fetchHint ? d->m_fetchHint->fetchHint() : QContactFetchHint());

    QContactIdFilter idFilter;
    idFilter.setIds(ids);
    if (d->m_filter) {
        QContactIntersectionFilter filter;
        filter.append(idFilter); // result handling assumes that id filter is the first filter
        filter.append(d->m_filter->filter());
        fetchRequest->setFilter(filter);
    } else
        fetchRequest->setFilter(idFilter);
    return fetchRequest;
}

QVariant QDeclarativeContactModel::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_contacts.count()) {
        return QVariant();
    }

    QDeclarativeContact* dc = d->m_contacts.value(index.row());
    Q_ASSERT(dc);
    QContact c = dc->contact();

    switch(role) {
        case Qt::DisplayRole:
             return c.detail(QContactDetail::TypeDisplayLabel).value(QContactDisplayLabel::FieldLabel);
        case Qt::DecorationRole:
            return QPixmap();
        case ContactRole:
            return QVariant::fromValue(dc);
    }
    return QVariant();
}


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

qsizetype  QDeclarativeContactModel::sortOrder_count(QQmlListProperty<QDeclarativeContactSortOrder> *p)
{
    QDeclarativeContactModel* model = qobject_cast<QDeclarativeContactModel*>(p->object);
    if (model)
        return model->d->m_sortOrders.size();
    return 0;
}

QDeclarativeContactSortOrder * QDeclarativeContactModel::sortOrder_at(QQmlListProperty<QDeclarativeContactSortOrder> *p, qsizetype idx)
{
    QDeclarativeContactModel* model = qobject_cast<QDeclarativeContactModel*>(p->object);

    QDeclarativeContactSortOrder* sortOrder = 0;
    if (model) {
        qsizetype i = 0;
        foreach (QDeclarativeContactSortOrder* s, model->d->m_sortOrders) {
            if (i == idx) {
                sortOrder = s;
                break;
            } else {
                i++;
            }
        }
    }
    return sortOrder;
}

void  QDeclarativeContactModel::sortOrder_clear(QQmlListProperty<QDeclarativeContactSortOrder> *p)
{
    QDeclarativeContactModel* model = qobject_cast<QDeclarativeContactModel*>(p->object);

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

/*!
  \qmlproperty list<Collection> OContactModel::collections

  This property holds a list of collections in the contact model.

  \sa Collection
  */
QQmlListProperty<QDeclarativeContactCollection> QDeclarativeContactModel::collections()
{
    return { this, nullptr, &collection_count, &collection_at };
}

qsizetype QDeclarativeContactModel::collection_count(QQmlListProperty<QDeclarativeContactCollection> *p)
{
    QDeclarativeContactModel* model = qobject_cast<QDeclarativeContactModel*>(p->object);
    return model ? model->d->m_collections.count() : 0;
}

QDeclarativeContactCollection *QDeclarativeContactModel::collection_at(QQmlListProperty<QDeclarativeContactCollection> *p, qsizetype idx)
{
    QDeclarativeContactModel* model = qobject_cast<QDeclarativeContactModel*>(p->object);
    QDeclarativeContactCollection* collection = 0;
    if (model) {
        if (!model->d->m_collections.isEmpty() && idx >= 0 && idx < model->d->m_collections.count())
            collection = model->d->m_collections.at(idx);
    }
    return collection;
}

/*!
    \internal

    It's invoked by the fetch request from onContactsAdded().
 */
void QDeclarativeContactModel::onContactsAddedFetchRequestStateChanged(QContactAbstractRequest::State state)
{

    if (state != QContactAbstractRequest::FinishedState)
        return;
    QContactFetchRequest *request = qobject_cast<QContactFetchRequest *>(sender());
    Q_ASSERT(request);

    checkError(request);

    if (request->error() == QContactManager::NoError) {
        QList<QContact> fetchedContacts(request->contacts());
        bool contactsAdded = false;
        foreach (const QContact &c,fetchedContacts) {
            if (d->m_contactMap.contains(c.id())) {
                qWarning() <<Q_FUNC_INFO <<"contact to be added already exists in the model";
                continue;
            }
            QDeclarativeContact* dc = new QDeclarativeContact(this);
            dc->setContact(c);
            int index = contactIndex(dc);
            beginInsertRows(QModelIndex(), index, index);
            d->m_contacts.insert(index, dc);
            d->m_contactMap.insert(c.id(), dc);
            if (!contactsAdded)
                contactsAdded = true;
            endInsertRows();
        }
        if (contactsAdded)
            emit contactsChanged();
    }
    request->deleteLater();
}


static bool contactListDoesNotContainContactWithId(const QList<QContact> &contactList, const QContactId &contactId) {
    foreach (const QContact &contact, contactList) {
        if (contact.id() == contactId)
            return false;
    }
    return true;
}

/*!
    \internal

    It's invoked by the fetch request from onContactsChanged().
 */
void QDeclarativeContactModel::onContactsChangedFetchRequestStateChanged(QContactAbstractRequest::State state)
{
    if (state != QContactAbstractRequest::FinishedState)
        return;

    QContactFetchRequest *request = qobject_cast<QContactFetchRequest *>(sender());
    Q_ASSERT(request);

    checkError(request);
    bool contactsUpdated = false;
    if (request->error() == QContactManager::NoError || request->error() == QContactManager::DoesNotExistError) {
        QList<QContact> fetchedContacts(request->contacts());
        QList<QContactId> requestedContactIds;
        //read requested contacts ids from the filter
        if (request->filter().type() == QContactFilter::IdFilter) {
            QContactIdFilter idFilter(request->filter());
            requestedContactIds = idFilter.ids();
        } else {
            QContactIntersectionFilter intersectionFilter(request->filter());
            QContactIdFilter idFilter(intersectionFilter.filters().at(0)); // assuming that id filter is the first filter
            requestedContactIds = idFilter.ids();
        }
        //handle updated contacts which needs removal from model
        //all contacts requested but not received are removed
        foreach (const QContactId &id, requestedContactIds) {
            if (contactListDoesNotContainContactWithId(fetchedContacts, id)) {
                for (int i=0;i<d->m_contacts.size();++i) {
                    if (d->m_contacts.at(i)->contactId() == id.toString()) {
                        beginRemoveRows(QModelIndex(), i, i);
                        // Remove and delete contact object
                        QDeclarativeContact* dc = d->m_contacts.takeAt(i);
                        dc->deleteLater();
                        d->m_contactMap.remove(id);
                        endRemoveRows();
                        contactsUpdated = true;
                    }
                }
            }
        }
        foreach (const QContact &fetchedContact, fetchedContacts) {
            QString contactIdString(fetchedContact.id().toString());
            bool fetchedContactFound = false;
            for (int i = 0; i < d->m_contacts.size(); ++i) {
                //handle updated contacts which should be updated in the model
                if (d->m_contacts.at(i)->contactId() == contactIdString) {
                    QDeclarativeContact* dc = d->m_contacts.at(i);
                    dc->setContact(fetchedContact);

                    // Since the contact can change the position due the sort order we need take care of it
                    // First we need to remove it from previous position and notify the model about that
                    beginRemoveRows(QModelIndex(), i, i);
                    d->m_contactMap.remove(fetchedContact.id());
                    d->m_contacts.removeAt(i);
                    endRemoveRows();

                    // Calculate the new position
                    int index = contactIndex(dc);
                    // Notify the model about the new item position
                    beginInsertRows(QModelIndex(), index, index);
                    d->m_contacts.insert(index, dc);
                    d->m_contactMap.insert(fetchedContact.id(),dc);
                    if (!contactsUpdated)
                        contactsUpdated = true;
                    endInsertRows();

                    fetchedContactFound = true;
                    break;
                }
            }
            //handle updated contacts which needs to be added in the model
            if (!fetchedContactFound) {
                QDeclarativeContact* dc = new QDeclarativeContact(this);
                dc->setContact(fetchedContact);
                int index = contactIndex(dc);
                beginInsertRows(QModelIndex(), index, index);
                d->m_contacts.insert(index, dc);
                d->m_contactMap.insert(fetchedContact.id(),dc);
                contactsUpdated = true;
                endInsertRows();
            }
        }
    }

    if (contactsUpdated)
        emit contactsChanged();

    request->deleteLater();
}

int QDeclarativeContactModel::contactIndex(const QDeclarativeContact* contact)
{
    if (d->m_sortOrders.count() > 0) {
        QList<QContactSortOrder> mSortOrders;
        foreach (QDeclarativeContactSortOrder *sortOrder, d->m_sortOrders)
            mSortOrders.append(sortOrder->sortOrder());
        for (int i = 0; i < d->m_contacts.size(); i++) {
            // check to see if the new contact should be inserted here
            int comparison = QContactManagerEngine::compareContact(d->m_contacts.at(i)->contact(),
                                                                   contact->contact(),
                                                                   mSortOrders);
            //if the contacts are equal or cannot be compared
            //we return the current position.The default case is if the new contact
            //should appear before the compared contact in m_contacts
            if (comparison >= 0)
                return i;
        }
    }
    return d->m_contacts.size();
}

QT_END_NAMESPACE

#include "moc_qdeclarativecontactmodel_p.cpp"