summaryrefslogtreecommitdiff
path: root/src/plugins/geoservices/nokia_places_jsondb/idreply.cpp
blob: d9e1db6ee92129f4a2f9f3aaf2476e70ada958cf (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
/****************************************************************************
**
** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: http://www.qt-project.org/
**
** This file is part of the QtLocation 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 "idreply.h"
#include "qplacemanagerengine_jsondb.h"
#include "jsonconverter.h"

#include <QtAddOnJsonDb/jsondb-client.h>
#include <QtAddOnJsonDb/jsondb-error.h>
#include <QtCore/QDebug>
#include <QtCore/QFile>
#include <QtCore/QUuid>


IdReply::IdReply(QPlaceIdReply::OperationType operationType,
                 QPlaceManagerEngineJsonDb *engine)
    : QPlaceIdReply(operationType, engine),m_engine(engine), m_isUpdate(false)
{
}

IdReply::~IdReply()
{
}

void IdReply::setId(const QString &id)
{
    QPlaceIdReply::setId(id);
}

bool IdReply::isUpdate() const
{
    return m_isUpdate;
}

void IdReply::setIsUpdate()
{
    m_isUpdate = true;
}

QString IdReply::parentCategoryId() const
{
    return m_parentCategoryId;
}

void IdReply::setParentCategoryId(const QString &parentId)
{
    m_parentCategoryId = parentId;
}

void IdReply::start()
{
}

SavePlaceReply::SavePlaceReply(QPlaceManagerEngineJsonDb *engine)
    : IdReply(QPlaceIdReply::SavePlace, engine), currIconIndex(0)
{
}

SavePlaceReply::~SavePlaceReply()
{
}

void SavePlaceReply::setPlace(const QPlace &place)
{
    m_place = place;
    setId(m_place.placeId());
}

void SavePlaceReply::start()
{
    connect(db(), SIGNAL(response(int,QVariant)), this, SLOT(processResponse(int,QVariant)));
    connect(db(), SIGNAL(error(int,int,QString)), this, SLOT(processError(int,int,QString)));

    if (m_place.visibility() & QtLocation::PublicVisibility) {
        triggerDone(QPlaceReply::UnsupportedError, QString::fromLatin1("Saving to public scope in unsupported"));
        return;
    } else {
        if (m_place.placeId().isEmpty()) {
            enterGetCategoriesState();
        } else {
            m_state = SavePlaceReply::CheckIfExists;
            m_reqId = db()->query(QString::fromLatin1("[?%1=\"%2\"][?%3 = \"%4\"]").arg(JsonConverter::Type).arg(JsonConverter::PlaceType)
                                  .arg(JsonConverter::Uuid).arg(m_place.placeId()));
        }
    }
}

void SavePlaceReply::enterGetCategoriesState()
{
    QVariantList categoryUuids;
    foreach (const QPlaceCategory &category, m_place.categories())
        categoryUuids.append(category.categoryId());

    QString queryString = QString::fromLatin1("[?%1=\"%2\"]").arg(JsonConverter::Type).arg(JsonConverter::CategoryType)
            + QString::fromLatin1("[?%1 in %categoryUuids]").arg(JsonConverter::Uuid);

    QVariantMap bindingsMap;
    bindingsMap.insert(QLatin1String("categoryUuids"), categoryUuids);

    QVariantMap queryObj;
    queryObj.insert(JsonConverter::Query, queryString);
    queryObj.insert(JsonConverter::Bindings, bindingsMap);

    m_state = SavePlaceReply::GetCategories;
    m_reqId = db()->find(queryObj);
}

void SavePlaceReply::enterGetIconsState()
{
    m_state = SavePlaceReply::GetIcons;
    QStringList prefixes;
    prefixes << "small" << "medium" << "large" << "fullscreen";

    QList<QUrl> uniqueInputUrls; //unique source urls that have been supplied without associated destinations
    foreach (const QString &prefix, prefixes) {
        bool ok;
        QUrl sourceUrl = convertToUrl(m_place.icon().parameters().value(prefix + QLatin1String("SourceUrl"), QUrl()), &ok);
        if (!ok) {
            triggerDone(QPlaceReply::BadArgumentError, QString::fromLatin1("icon parameter for key: ") + prefix + QLatin1String("SourceUrl")
                        + QLatin1String(" was not a QUrl object"));
            return;
        }
        QUrl destinationUrl = convertToUrl(m_place.icon().parameters().value(prefix + QLatin1String("Url"), QUrl()), &ok);
        if (!ok) {
            triggerDone(QPlaceReply::BadArgumentError, QString::fromLatin1("icon parameter for key: ") + prefix + QLatin1String("Url")
                        + QLatin1String(" was not a QUrl object"));
            return;
        }

        if (destinationUrl.isEmpty()) {
            if (sourceUrl.isEmpty() || uniqueInputUrls.contains(sourceUrl))
                continue;
            else
                uniqueInputUrls.append(sourceUrl);
        }

        QString destination;
        if (!destinationUrl.isEmpty())
            destination = prefix + QLatin1String("Url");

        Icon *icon = new Icon(sourceUrl, destinationUrl, destination);
        if (m_place.icon().parameters().contains(prefix + QLatin1String("Size")))
            icon->setSpecifiedSize(m_place.icon().parameters().value(prefix + QLatin1String("Size")).toSize());

        m_icons.append(icon);
    }

    processIcons();
}

void SavePlaceReply::processIcons()
{
    if (qobject_cast<Icon *>(sender())) {
        Icon *senderIcon = qobject_cast<Icon *>(sender());
        if (senderIcon->error() != QPlaceReply::NoError) {
            triggerDone(senderIcon->error(), senderIcon->errorString());
            return;
        }
    }

    if (currIconIndex < m_icons.count()) {
        Icon *icon = m_icons.at(currIconIndex);
        connect(icon, SIGNAL(initializationFinished()), this, SLOT(processIcons()), Qt::QueuedConnection);
        icon->initialize();
        currIconIndex++;
        return;
    } else {
        QVariantMap thumbnailsMap;
        QVariantMap thumbnailMap;

        bool error = false;

        //try to set destinations for icons which were not already set
        QStringList specifiedDestinations;
        foreach (Icon *icon, m_icons) {
            if (!icon->destination().isEmpty())
                specifiedDestinations.append(icon->destination());
        }

        //try to set small,medium and large destinations if they haven't already been explicitly specified
        //and there are icons with unspecified destinations. (essentially we are creating data urls if necessary)
        if (!specifiedDestinations.contains(Icon::SmallDestination))
            trySetDestination(Icon::SmallDestination);

        if (!specifiedDestinations.contains(Icon::MediumDestination))
            trySetDestination(Icon::MediumDestination);

        if (!specifiedDestinations.contains(Icon::LargeDestination))
            trySetDestination(Icon::LargeDestination);

        //Note that we don't try and set the destination for full screen thumbnails
        //since data urls are meant to be just for small images

        foreach (Icon *icon, m_icons) {
            thumbnailMap.clear();
            if (icon->error() != QPlaceReply::NoError) {
                triggerDone(icon->error(), icon->errorString());
                error = true;
                break;
            }

            if (!icon->sourceUrl().isEmpty()
                    && icon->destinationUrl().scheme().compare(QLatin1String("file")) == 0) {
                if (!icon->copy()) {
                    triggerDone(icon->error(), icon->errorString());
                    error = true;
                    break;
                }
            }

            thumbnailMap.insert(JsonConverter::Url, icon->destinationUrl().toString());
            if (icon->size().isValid()) {
                thumbnailMap.insert(JsonConverter::Height, icon->size().height());
                thumbnailMap.insert(JsonConverter::Width, icon->size().width());
            } else {
                //size of icon could not be calculated, therefore rely on manually specified size
                if (!icon->specifiedSize().isValid()) {
                    triggerDone(QPlaceReply::BadArgumentError, QLatin1String("Size of icon could not be generated nor was it validly specified"));
                    error = true;
                    break;
                }
                thumbnailMap.insert(JsonConverter::Height, icon->specifiedSize().height());
                thumbnailMap.insert(JsonConverter::Width, icon->specifiedSize().width());
            }

            if (icon->destination() == Icon::SmallDestination)
                thumbnailsMap.insert(JsonConverter::Small, thumbnailMap);
            else if (icon->destination() == Icon::MediumDestination)
                thumbnailsMap.insert(JsonConverter::Medium, thumbnailMap);
            else if (icon->destination() == Icon::LargeDestination)
                thumbnailsMap.insert(JsonConverter::Large, thumbnailMap);
            else
                thumbnailsMap.insert(JsonConverter::Fullscreen, thumbnailMap);
        }

        if (!error) {
            m_placeMap.insert(JsonConverter::Thumbnails, thumbnailsMap);

            //proceed to save
            m_state = SavePlaceReply::Saving;
            if (m_place.placeId().isEmpty())
                m_reqId = db()->create(m_placeMap);
            else
                m_reqId = db()->update(m_placeMap);
        }

        qDeleteAll(m_icons);
        m_icons.clear();
    }
}

void SavePlaceReply::processResponse(int id, const QVariant &data)
{
    if (id != m_reqId)
        return;

    if (m_state == SavePlaceReply::CheckIfExists) {
        if (data.toMap().value(JsonConverter::Length).toInt() == 0) {
            triggerDone(QPlaceReply::PlaceDoesNotExistError, QString::fromLatin1("Specified place does not exist"));
            return;
        }

        m_placeMap = data.toMap().value(JsonConverter::Data).toList().first().toMap();

        enterGetCategoriesState();
    } else if (m_state == SavePlaceReply::GetCategories) {
        if (data.toMap().value(JsonConverter::Length).toInt() < m_place.categories().count()) {
            triggerDone(QPlaceReply::CategoryDoesNotExistError,
                            QLatin1String("Specified categories does not exist for place"));
            return;
        } else if (data.toMap().value(JsonConverter::Length).toInt() > m_place.categories().count()) {
            triggerDone(QPlaceReply::UnknownError,
                        QLatin1String("Too many categories found for a place")); //should never happen
            return;
        }

        QList<QVariantMap> categoriesJson = JsonConverter::convertToListOfMaps(data);
        QStringList allCategoryUuids;
        foreach (const QVariantMap categoryMap, categoriesJson)
            allCategoryUuids.append(categoryMap.value(JsonConverter::Ancestors).toStringList());
        allCategoryUuids.removeDuplicates();

        m_placeMap.insert(JsonConverter::AllCategoryUuids, allCategoryUuids);
        m_placeMap = JsonConverter::addToJsonMap(m_placeMap, m_place);

        enterGetIconsState();
        return;
    } else if (m_state == SavePlaceReply::Saving) {
        /*
        Expected data format
        {
        "uuid":<uuid>,
        "_version": <version>
        }*/
        setId(data.toMap().value(JsonConverter::Uuid).toString());
        triggerDone();
    }
}

void SavePlaceReply::processError(int id, int code, const QString &jsonDbErrorString)
{
    if (id != m_reqId)
        return;

    if (m_state == SavePlaceReply::CheckIfExists) {
        triggerDone(QPlaceReply::UnknownError, QString::fromLatin1("Error saving place from jsondb, could not "
                                                              "determine if place exists"));
        return;
    }

    if (code == JsonDbError::MissingObject) {
        triggerDone(QPlaceReply::PlaceDoesNotExistError, QLatin1String("Place does not exist"));
        return;
    } else {
        QPlaceReply::Error error = QPlaceReply::UnknownError;
        QString errorString = QString::fromLatin1("Unknown error occurred during save place operation: jsondb error code =%1, erroString=%2")
                      .arg(code).arg(jsonDbErrorString);
        triggerDone(error, errorString);
        return;
    }
}

void SavePlaceReply::trySetDestination(const QString &destination)
{
    static int threshold;
    int height;

    //assumption is that icons are squarish
    //so we can rely on height as a means to detect which size bucket
    //the icon belongs to
    if (destination == Icon::SmallDestination) {
        threshold = (Icon::SmallSize.height() + Icon::MediumSize.height()) / 2;
        height = Icon::SmallSize.height();
    } else if (destination == Icon::MediumDestination) {
        threshold = (Icon::MediumSize.height() + Icon::LargeSize.height()) / 2;
        height = Icon::MediumSize.height();
    } else if (destination == Icon::LargeDestination) {
        threshold = Icon::LargeSize.height() * 2;
        height = Icon::LargeSize.height();
    } //note fullscreen thumbnails should not be set as data urls.

    Icon *currIcon = 0;
    foreach (Icon *icon, m_icons) {
        if (icon->destination().isEmpty()
                && icon->size().height() < threshold
                && (currIcon == 0 ||  qAbs(icon->size().height() - height) < qAbs(currIcon->size().height() - height))) {
            if (currIcon)
                currIcon->setDestination(QString());
            currIcon = icon;
            currIcon->setDestination(destination);
        }
    }
    if (currIcon)
        currIcon->setDestinationDataUrl();
}

QUrl SavePlaceReply::convertToUrl(const QVariant &var, bool *ok)
{
    if (ok)
        *ok = false;

    switch (var.type()) {
    case (QVariant::Url): {
        if (ok)
            *ok = true;
        QUrl url = var.toUrl();
        if (url.scheme().isEmpty())
            return QUrl::fromUserInput(url.toString());
        else
            return url;
        break;
    }
    default:
        return QUrl();
    }
}

//-------RemovePlaceReply

RemovePlaceReply::RemovePlaceReply(QPlaceManagerEngineJsonDb *engine)
    : IdReply(QPlaceIdReply::RemovePlace, engine)
{
}

RemovePlaceReply::~RemovePlaceReply()
{
}

void RemovePlaceReply::setId(const QString &placeId)
{
    IdReply::setId(placeId);
}

void RemovePlaceReply::start()
{
    connect(db(), SIGNAL(response(int,QVariant)), this, SLOT(processResponse(int,QVariant)));
    connect(db(), SIGNAL(error(int,int,QString)), this, SLOT(processError(int,int,QString)));

    QVariantMap jsonMap;
    jsonMap.insert(JsonConverter::Uuid, id());
    jsonMap.insert(JsonConverter::Type, JsonConverter::PlaceType);
    m_reqId = db()->remove(jsonMap);
}

void RemovePlaceReply::processResponse(int id, const QVariant &data)
{
    if (id != m_reqId)
        return;

    /*
        Expected data format example
        {
        "count":1,
        "data":[
            {
            "_uuid":"8c196304-509c-5c45-0a07-0ea25a280f10523d"
            }],
        "error":[]
        }
    */
    QVariantMap jsonResponse = data.toMap();
    if (jsonResponse.value(QLatin1String("count")).toInt() <= 0) {
        triggerDone(QPlaceReply::UnknownError,
                             QString::fromLatin1("JsonDb response does not contain a uuid"
                                "for a removal request"));
        return;
    } else {
        QVariantMap jsonResponse = data.toMap();
        QString uuid = jsonResponse.value(JsonConverter::Data)
                .toList().at(0).toMap().value(JsonConverter::Uuid).toString();
        if (uuid != IdReply::id()) {
            triggerDone(QPlaceReply::UnknownError,
                                 QString::fromLatin1("JsonDb Response UUID does not match that in request"
                                    "for a removal operation\n"
                                    "JsonDb UUID: %1"
                                    "Request UUID: %2").arg(uuid).arg(IdReply::id()));
            return;
        } else {
            triggerDone();
            return;
        }
    }
}

void RemovePlaceReply::processError(int id, int code, const QString &jsonDbErrorString)
{
    if (id != m_reqId)
        return;

    if (code == JsonDbError::MissingObject) {
        triggerDone(QPlaceReply::PlaceDoesNotExistError, QLatin1String("Place does not exist"));
        return;
    } else {
        QPlaceReply::Error error = QPlaceReply::UnknownError;
        QString errorString = QString::fromLatin1("Unknown error occurred during remove place operation: jsondb error code =%1, erroString=%2").
                      arg(code).arg(jsonDbErrorString);
        triggerDone(error, errorString);
        return;
    }
}

//-------SaveCategoryReply

SaveCategoryReply::SaveCategoryReply(QPlaceManagerEngineJsonDb *engine)
    : IdReply(QPlaceIdReply::SaveCategory, engine)
{
}

SaveCategoryReply::~SaveCategoryReply()
{
}

void SaveCategoryReply::setCategory(const QPlaceCategory &category)
{
    m_category = category;
}

void SaveCategoryReply::setParentId(const QString &parentId)
{
    m_parentId = parentId;
}

void SaveCategoryReply::start()
{
   connect(db(), SIGNAL(response(int,QVariant)), this, SLOT(processResponse(int,QVariant)));
   connect(db(), SIGNAL(error(int,int,QString)), this, SLOT(processError(int,int,QString)));


    //check if parentExists
   if (!m_parentId.isEmpty()) {
       m_state = SaveCategoryReply::CheckParentExists;
       m_reqId = db()->query(m_engine->queryCategoryString(m_parentId));
   } else {
       doSave();
   }
}

void SaveCategoryReply::doSave()
{
    m_state = Saving;

    if (m_category.categoryId().isEmpty())
        m_category.setCategoryId(QUuid::createUuid().toString());
    QVariantMap categoryMap = JsonConverter::convertToJsonMap(m_category);

    m_newAncestors.append(m_category.categoryId());
    categoryMap.insert(JsonConverter::Ancestors, m_newAncestors);
    categoryMap.insert(JsonConverter::CategoryParentId,  m_parentId);
    m_reqId = db()->update(categoryMap);
}

void SaveCategoryReply::processResponse(int id, const QVariant &data)
{
    if (id != m_reqId)
        return;

    if (m_state == SaveCategoryReply::CheckParentExists) {
        if (data.toMap().value(JsonConverter::Length).toInt() <= 0) {
            triggerDone(QPlaceReply::CategoryDoesNotExistError, "Parent category does not exist");
            return;
        }

        QVariantMap parentMap = data.toMap().value(JsonConverter::Data).toList().at(0).toMap();
        m_newAncestors = parentMap.value(JsonConverter::Ancestors).toStringList();

        if (!m_category.categoryId().isEmpty()) {
            m_state = SaveCategoryReply::GetCurrentCategory;
            m_reqId = db()->query(m_engine->queryCategoryString(m_category.categoryId()));
            return;
        }

        doSave();
    } else if (m_state == SaveCategoryReply::GetCurrentCategory) {
        if (data.toMap().value(JsonConverter::Length).toInt() == 0) {
            triggerDone(QPlaceReply::CategoryDoesNotExistError, "Category does not exist");
            return;
        }

        QVariantMap categoryMap = data.toMap().value(JsonConverter::Data).toList().first().toMap();
        m_oldAncestors = categoryMap.value(JsonConverter::Ancestors).toStringList();
        m_oldAncestors.removeLast();  //remove the current category from the ancestor list

        //if the new parent is different from the old, if so we need to change the ancestors
        //of the category and it's descendents
        if (m_parentId != categoryMap.value(JsonConverter::CategoryParentId)) {

            QString getDescendantsQuery = QString("[?%1=\"%2\"]").arg(JsonConverter::Type).arg(JsonConverter::CategoryType);
            foreach (const QVariant &ancestor, m_oldAncestors)
                getDescendantsQuery += QString("[?%1 contains \"%2\"]").arg(JsonConverter::Ancestors).arg(ancestor.toString());

            m_reqId = db()->query(getDescendantsQuery);
            m_state = SaveCategoryReply::GetParentDescendants;
        } else {
            m_state = SaveCategoryReply::Saving;
            m_reqId = db()->update(JsonConverter::addToJsonMap(categoryMap, m_category));
        }

    } else if (m_state == SaveCategoryReply::GetParentDescendants) {
        if (data.toMap().value(JsonConverter::Data).toList().length() == 0) {
            triggerDone(QPlaceReply::CategoryDoesNotExistError, QLatin1String("Category could not be found while searching for the parent's "
                                                                "descendants"));
            return;
        }

        QStringList ancestors;
        QStringList newAncestors;
        QVariantList jsonMapCategories;
        QVariantMap categoryMap;
        foreach (QVariant var, data.toMap().value(JsonConverter::Data).toList()) {
            categoryMap = var.toMap();
            ancestors = categoryMap.value(JsonConverter::Ancestors).toStringList();

            for (int i = 0; i < m_oldAncestors.count(); ++i)
               ancestors.removeFirst();

            newAncestors = m_newAncestors;
            newAncestors.append(ancestors);

            categoryMap.insert(JsonConverter::Ancestors, newAncestors);

            if (categoryMap.value(JsonConverter::Uuid).toString() == m_category.categoryId()) {
                categoryMap = JsonConverter::addToJsonMap(categoryMap, m_category);
                categoryMap.insert(JsonConverter::CategoryParentId, m_parentId);
            }

            jsonMapCategories.append(categoryMap);
        }

        m_state = SaveCategoryReply::Saving;
        m_reqId = db()->update(jsonMapCategories);

    } else if (m_state == SaveCategoryReply::Saving) {
        if (data.type() == QVariant::Map) {
            setId(data.toMap().value(JsonConverter::Uuid).toString());
            triggerDone();
        } else if (data.type() == QVariant::List) {
            setId(m_category.categoryId());
            triggerDone();
        }
    }
}

void SaveCategoryReply::processError(int id, int code, const QString &jsonDbErrorString)
{
    if (id != m_reqId)
        return;

    if (code == JsonDbError::MissingObject) {
        triggerDone(QPlaceReply::CategoryDoesNotExistError, QLatin1String("Category does not exist"));
        return;
    } else {
        QPlaceReply::Error error = QPlaceReply::UnknownError;
        QString errorString = QString::fromLatin1("Unknown error occurred during save category operation: "
                                                  "jsondb error code = %1, erroString = %2")
                      .arg(code).arg(jsonDbErrorString);
        triggerDone(error, errorString);
        return;
    }
}

//-------RemoveCategoryReply

RemoveCategoryReply::RemoveCategoryReply(QPlaceManagerEngineJsonDb *engine)
    : IdReply(QPlaceIdReply::RemovePlace, engine)
{
}

RemoveCategoryReply::~RemoveCategoryReply()
{
}

void RemoveCategoryReply::setId(const QString &categoryId)
{
    IdReply::setId(categoryId);
}

void RemoveCategoryReply::start()
{
    connect(db(), SIGNAL(response(int,QVariant)), this, SLOT(processResponse(int,QVariant)));
    connect(db(), SIGNAL(error(int,int,QString)), this, SLOT(processError(int,int,QString)));

    m_state = RemoveCategoryReply::GetCategory;
    m_reqId = db()->query(m_engine->queryCategoryString(id()));
}

void RemoveCategoryReply::processResponse(int id, const QVariant &data)
{
    if (id != m_reqId)
        return;

    //TODO: need to handle removal of category related information still
    //      in the Place objects
    switch (m_state) {
    case (RemoveCategoryReply::GetCategory) : {
        /*
            Expected data format example
            {
            "count":1,
            "data":[
                {
                "_uuid":"8c196304-509c-5c45-0a07-0ea25a280f10523d"
                }],
            "error":[]
            }
        */
        if (data.toMap().value(JsonConverter::Length).toInt() <= 0) {
            triggerDone(QPlaceReply::CategoryDoesNotExistError,
                        QLatin1String("Trying to remove category that does not exist"));
            return;
        } else {
             QVariantMap categoryMap = data.toMap().value(JsonConverter::Data)
                                        .toList().at(0).toMap();
            QString uuid = categoryMap.value(JsonConverter::Uuid).toString();
            if (uuid != IdReply::id()) {
                triggerDone(QPlaceReply::UnknownError,
                            QString::fromLatin1(" Response UUID does not match that in the request"
                               "for a category removal"
                               "JsonDb UUID: %1"
                               "Request UUID: %2").arg(uuid).arg(IdReply::id()));
                return;
            } else {
                QString queryString = QString::fromLatin1("[?%1=\"%2\"]").arg(JsonConverter::Type).arg(JsonConverter::CategoryType);
                QStringList ancestors = categoryMap.value(JsonConverter::Ancestors).toStringList();
                foreach (const QString &ancestor, ancestors)
                    queryString += QString::fromLatin1("[?%1 contains \"%2\"]").arg(JsonConverter::Ancestors).arg(ancestor);

                m_state = RemoveCategoryReply::GetCategoriesToBeRemoved;
                m_reqId = db()->query(queryString);
            }
        }
        break;
    }
    case (RemoveCategoryReply::GetCategoriesToBeRemoved) : {
        QVariant categoriesJson = data.toMap().value("data");
        m_state = RemoveCategoryReply::RemoveCategories;
        m_reqId = db()->remove(categoriesJson);
        break;
    }
    case (RemoveCategoryReply::RemoveCategories) : {
        triggerDone();
    }
    }
}

void RemoveCategoryReply::processError(int id, int code, const QString &jsonDbErrorString)
{
    if (id != m_reqId)
        return;

    if (code == JsonDbError::MissingObject) {
        triggerDone(QPlaceReply::CategoryDoesNotExistError, QLatin1String("Category does not exist"));
        return;
    } else {
        QPlaceReply::Error error = QPlaceReply::UnknownError;
        QString errorString = QString::fromLatin1("Unknown error occurred during remove place operation: jsondb error code =%1, erroString=%2").
                      arg(code).arg(jsonDbErrorString);
        triggerDone(error, errorString);
        return;
    }
}