File: configobject.cc

package info (click to toggle)
qdmr 0.13.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 22,420 kB
  • sloc: cpp: 95,929; xml: 10,749; python: 1,108; makefile: 78; sh: 9
file content (1578 lines) | stat: -rw-r--r-- 54,233 bytes parent folder | download
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
#include "configobject.hh"
#include "configreference.hh"
#include "logger.hh"
#include "frequency.hh"
#include "interval.hh"
#include "signaling.hh"

#include <QMetaProperty>
#include <QMetaEnum>

// Helper function to extract key names for a QMetaEnum
inline QStringList enumKeys(const QMetaEnum &e) {
  QStringList lst;
  for (int i=0; i<e.keyCount(); i++)
    lst.push_back(e.key(i));
  return lst;
}

inline bool isInstanceOf(QObject *obj, const QStringList &typeNames) {
  const QMetaObject *type = obj->metaObject();
  while (type) {
    if (typeNames.contains(type->className()))
      return true;
    type = type->superClass();
  }
  return false;
}


/* ********************************************************************************************* *
 * Implementation of ConfigObject::Context
 * ********************************************************************************************* */
QHash<QString, QHash<QString, ConfigObject *>> ConfigObject::Context::_tagObjects =
    QHash<QString, QHash<QString, ConfigObject *>>();
QHash<QString, QHash<ConfigObject *, QString>> ConfigObject::Context::_tagNames =
    QHash<QString, QHash<ConfigObject *, QString>>();

ConfigItem::Context::Context()
  : _version(), _objects(), _ids()
{
  // pass...
}

ConfigItem::Context::~Context() {
  // pass...
}

const QString &
ConfigItem::Context::version() const {
  return _version;
}
void
ConfigItem::Context::setVersion(const QString &ver) {
  _version = ver;
}

bool
ConfigItem::Context::contains(ConfigObject *obj) const {
  return _ids.contains(obj);
}

bool
ConfigItem::Context::contains(const QString &id) const {
  return _objects.contains(id);
}

QString
ConfigItem::Context::getId(ConfigObject *obj) const {
  return _ids.value(obj, "");
}

ConfigObject *
ConfigItem::Context::getObj(const QString &id) const {
  return _objects.value(id, nullptr);
}

bool
ConfigItem::Context::add(const QString &id, ConfigObject *obj) {
  if (_objects.contains(id) || _ids.contains(obj))
    return false;
  _objects.insert(id, obj);
  _ids.insert(obj, id);
  return true;
}

bool
ConfigItem::Context::hasTag(const QString &className, const QString &property, const QString &tag) {
  QString qname = className+"::"+property;
  return _tagObjects.contains(qname) && _tagObjects[qname].contains(tag);
}

bool
ConfigItem::Context::hasTag(const QString &className, const QString &property, ConfigObject *obj) {
  QString qname = className+"::"+property;
  return _tagNames.contains(qname) && _tagNames[qname].contains(obj);
}

ConfigObject *
ConfigItem::Context::getTag(const QString &className, const QString &property, const QString &tag) {
  //logDebug() << "Request " << tag << " for " << property << " in " << className << ".";
  QString qname = className+"::"+property;
  if (! _tagObjects.contains(qname))
    return nullptr;
  return _tagObjects[qname].value(tag, nullptr);
}

QString
ConfigItem::Context::getTag(const QString &className, const QString &property, ConfigObject *obj) {
  //logDebug() << "Request tag for " << property << " in " << className << ".";
  QString qname = className+"::"+property;
  if (! _tagNames.contains(qname))
    return nullptr;
  return _tagNames[qname].value(obj);
}

void
ConfigItem::Context::setTag(const QString &className, const QString &property, const QString &tag, ConfigObject *obj) {
  //logDebug() << "Register tag " << tag << " for " << property << " in " << className << ".";
  QString qname = className+"::"+property;
  if (! _tagObjects.contains(qname))
    _tagObjects[qname] = QHash<QString, ConfigObject*>();
  _tagObjects[qname].insert(tag, obj);
  if (! _tagNames.contains(qname))
    _tagNames[qname] = QHash<ConfigObject*, QString>();
  _tagNames[qname].insert(obj, tag);
}


/* ********************************************************************************************* *
 * Implementation of ConfigItem
 * ********************************************************************************************* */
ConfigItem::ConfigItem(QObject *parent)
  : QObject(parent)
{
  // pass...
}

bool
ConfigItem::copy(const ConfigItem &other) {
  // check if other has the same type
  if (strcmp(other.metaObject()->className(), metaObject()->className())) {
    logError() << metaObject()->className() << " cannot copy from "
               << other.metaObject()->className();
    return false;
  }

  // clear this instance
  this->clear();

  // Iterate over all properties
  const QMetaObject *meta = metaObject();
  for (int p=QObject::staticMetaObject.propertyCount(); p<meta->propertyCount(); p++) {
    // This property
    QMetaProperty prop = meta->property(p);
    // the same property over at other
    QMetaProperty oprop = other.metaObject()->property(p);

    // Should never happen
    if (! prop.isValid()) {
      logWarn() << "Invalid property " << prop.name() << ". This should not happen.";
      continue;
    }

    // true if the property is a basic type
    bool isBasicType = ( prop.isEnumType() || (QMetaType::Bool==prop.typeId()) ||
                         (QMetaType::Int==prop.typeId()) || (QMetaType::UInt==prop.typeId()) ||
                         (QMetaType::Double==prop.typeId()) || (QMetaType::QString==prop.typeId()) ||
                         (QString("Frequency")==prop.typeName()) ||
                         (QString("Interval")==prop.typeName()) );

    // If a basic type -> simply copy value
    if (isBasicType && prop.isWritable() && (prop.typeId()==oprop.typeId())) {
      if (! prop.write(this, oprop.read(&other))) {
        logError() << "Cannot set property '" << prop.name() << "' of "
                   << this->metaObject()->className() << ".";
        return false;
      }
    } else if (ConfigObjectReference *ref = prop.read(this).value<ConfigObjectReference *>()) {
      if (! ref->copy(oprop.read(&other).value<ConfigObjectReference*>())) {
        logError() << "Cannot copy object reference '" << prop.name() << "' of "
                   << this->metaObject()->className() << ".";
        return false;
      }
    } else if (ConfigObjectList *lst = prop.read(this).value<ConfigObjectList *>()) {
      if (! lst->copy(*oprop.read(&other).value<ConfigObjectList*>())) {
        logError() << "Cannot copy object list '" << prop.name() << "' of "
                   << this->metaObject()->className() << ".";
        return false;
      }
    } else if (ConfigObjectRefList *lst = prop.read(this).value<ConfigObjectRefList *>()) {
      if (! lst->copy(*oprop.read(&other).value<ConfigObjectRefList*>())) {
        logError() << "Cannot copy reference list '" << prop.name() << "' of "
                   << this->metaObject()->className() << ".";
        return false;
      }
    } else if (propIsInstance<ConfigItem>(prop)) {
      // If the item is owned by this item
      if (prop.isWritable()) {
        // If the owned item is writeable -> clone if set in other
        if (oprop.read(&other).isNull()) {
          if ((! prop.read(&other).isNull()) && (! prop.write(this, QVariant(prop.metaType())))) {
            logError() << "Cannot delete item '" << prop.name() << "' of "
                       << this->metaObject()->className() << ".";
            return false;
          }
        } else {
          // Clone element form other item
          ConfigItem *cl = oprop.read(&other).value<ConfigItem*>()->clone();
          if (nullptr == cl) {
            logError() << "Cannot clone item '" << oprop.name() << "' of "
                       << other.metaObject()->className() << ".";
            return false;
          }
          // Write clone
          if (! prop.write(this, QVariant(prop.metaType(), &cl))) {
            logError() << "Cannot replace item '" << prop.name() << "' of "
                       << this->metaObject()->className() << ".";
            cl->deleteLater();
            return false;
          }
        }
      } else if (! oprop.read(&other).isNull()) {
        // If the owned item is not writable (must be present) -> copy from other if set
        if (! prop.read(this).value<ConfigItem*>()->copy(*oprop.read(&other).value<ConfigItem*>())) {
          logError() << "Cannot copy fixed item '" << prop.name() << "' of "
                     << this->metaObject()->className() << ".";
          return false;
        }
      }
    }
  }

  emit modified(this);
  return true;
}

int
ConfigItem::compare(const ConfigItem &other) const {
  // Check if other has the same type
  if (strcmp(other.metaObject()->className(), metaObject()->className()))
    return strcmp(metaObject()->className(), other.metaObject()->className());

  // Compare by properties
  const QMetaObject *meta = metaObject();
  for (int p=QObject::staticMetaObject.propertyCount(); p<meta->propertyCount(); p++) {
    // This property
    QMetaProperty prop = meta->property(p);
    // the same property over at other
    QMetaProperty oprop = other.metaObject()->property(p);

    // Should never happen
    if (! prop.isValid())
      continue;

    // Handle comparison of basic types
    if ((prop.isEnumType()) || (QMetaType::Bool == prop.typeId()) || (QMetaType::Int == prop.typeId()) || (QMetaType::UInt == prop.typeId())) {
      int a=prop.read(this).toInt(), b=oprop.read(&other).toInt();
      if (a<b)
        return -1;
      if (a>b)
        return 1;
      continue;
    }

    if (QMetaType::Double == prop.typeId()) {
      double a=prop.read(this).toDouble(), b=oprop.read(&other).toDouble();
      if (a<b)
        return -1;
      if (a>b)
        return 1;
      continue;
    }

    if (QMetaType::QString == prop.typeId()) {
      int cmp = QString::compare(prop.read(this).toString(), oprop.read(&other).toString());
      if (cmp)
        return cmp;
      continue;
    }

    if (QString("Frequency") == prop.typeName()) {
      Frequency a = prop.read(this).value<Frequency>(), b = oprop.read(&other).value<Frequency>();
      if (a<b)
        return -1;
      if (b<a)
        return 1;
      continue;
    }

    if (QString("Interval") == prop.typeName()) {
      Interval a = prop.read(this).value<Interval>(), b = oprop.read(&other).value<Interval>();
      if (a<b)
        return -1;
      if (b<a)
        return 1;
      continue;
    }

    if (ConfigObjectReference *ref = prop.read(this).value<ConfigObjectReference *>()) {
      int cmp = ref->compare(*oprop.read(&other).value<ConfigObjectReference*>());
      if (cmp)
        return cmp;
      continue;
    }

    if (ConfigObjectList *lst = prop.read(this).value<ConfigObjectList *>()) {
      int cmp = lst->compare(*oprop.read(&other).value<ConfigObjectList*>());
      if (cmp)
        return cmp;
      continue;
    }

    if (propIsInstance<ConfigObjectRefList>(prop)) {
      ConfigObjectRefList *lst = prop.read(this).value<ConfigObjectRefList *>();
      int cmp = lst->compare(*oprop.read(&other).value<ConfigObjectRefList*>());
      if (cmp)
        return cmp;
      continue;
    }

    if (propIsInstance<ConfigItem>(prop)) {
      // If the owned item is writeable -> clone if set in other
      if (prop.read(this).isNull() && !oprop.read(&other).isNull())
        return -1;
      if (!prop.read(this).isNull() && oprop.read(&other).isNull())
        return 1;
      if (prop.read(this).isNull() && oprop.read(&other).isNull())
        continue;
      int cmp = prop.read(this).value<ConfigItem*>()->compare(*oprop.read(&other).value<ConfigItem*>());
      if (cmp)
        return cmp;
      continue;
    }
  }

  return 0;
}


bool
ConfigItem::label(ConfigObject::Context &context, const ErrorStack &err) {
  // Label properties owning config objects, that is of type ConfigObject or ConfigObjectList
  const QMetaObject *meta = metaObject();

  for (int p=QObject::staticMetaObject.propertyCount(); p<meta->propertyCount(); p++) {
    QMetaProperty prop = meta->property(p);
    if (! prop.isValid())
      continue;
    if (prop.read(this).value<ConfigObjectList *>()) {
      ConfigObjectList *lst = prop.read(this).value<ConfigObjectList *>();
      if (! lst->label(context, err))
        return false;
    } else if (prop.read(this).value<ConfigItem *>()) {
      ConfigItem *obj = prop.read(this).value<ConfigItem *>();
      if (! obj->label(context, err))
        return false;
    }
  }

  return true;
}


YAML::Node
ConfigItem::serialize(const Context &context, const ErrorStack &err) {
  YAML::Node node;
  if (! populate(node, context, err))
    return YAML::Node();
  return node;
}

void
ConfigItem::clear() {
  emit beginClear();

  // Delete or clear all object owned by properties, that is ConfigObjectList and ConfigObject
  const QMetaObject *meta = metaObject();
  for (int p=QObject::staticMetaObject.propertyCount(); p<meta->propertyCount(); p++) {
    QMetaProperty prop = meta->property(p);
    if (! prop.isValid())
      continue;
    if (propIsInstance<ConfigItem>(prop) && prop.isWritable()) {
      prop.write(this, QVariant(prop.metaType()));
    } else if (ConfigObjectList *lst = prop.read(this).value<ConfigObjectList *>()) {
      lst->clear();
    }
  }

  emit endClear();
}

bool
ConfigItem::populate(YAML::Node &node, const Context &context, const ErrorStack &err){
  // Serialize all properties
  const QMetaObject *meta = metaObject();
  for (int p=QObject::staticMetaObject.propertyCount(); p<meta->propertyCount(); p++) {
    QMetaProperty prop = meta->property(p);
    if (! prop.isValid())
      continue;
    if (! prop.isScriptable()) {
      /*logDebug() << "Do not serialize property '"
                 << prop.name() << "': Marked as not scriptable.";*/
      continue;
    }
    if (prop.isEnumType()) {
      QMetaEnum e = prop.enumerator();
      QVariant value = prop.read(this);
      const char *key = e.valueToKey(value.toInt());
      if (nullptr == key) {
        errMsg(err) << "Cannot map value " << value.toUInt()
                    << " to enum " << e.name()
                    << ". Ignore attribute '" << prop.name()
                    << "' but this points to an incompatibility in some codeplug. "
                    << "Consider reporting it to https://github.com/hmatuschek/qdmr/issues.";
        continue;
      }
      node[prop.name()] = key;
    } else if (QString("bool") == prop.typeName()) {
      node[prop.name()] = this->property(prop.name()).toBool();
    } else if (QString("int") == prop.typeName()) {
      node[prop.name()] = this->property(prop.name()).toInt();
    } else if (QString("uint") == prop.typeName()) {
      node[prop.name()] = this->property(prop.name()).toUInt();
    } else if (QString("double") == prop.typeName()) {
      node[prop.name()] = this->property(prop.name()).toDouble();
    } else if (QString("QString") == prop.typeName()) {
      node[prop.name()] = this->property(prop.name()).toString().toStdString();
    } else if (QString("Frequency") == prop.typeName()) {
      node[prop.name()] = this->property(prop.name()).value<Frequency>();
    } else if (QString("Interval") == prop.typeName()) {
      node[prop.name()] = this->property(prop.name()).value<Interval>();
    } else if (QString("SelectiveCall") == prop.typeName()) {
      node[prop.name()] = this->property(prop.name()).value<SelectiveCall>();
    } else if (ConfigObjectReference *ref = prop.read(this).value<ConfigObjectReference *>()) {
      ConfigObject *obj = ref->as<ConfigObject>();
      if (nullptr == obj)
        continue;
      if (context.hasTag(prop.enclosingMetaObject()->className(), prop.name(), obj)) {
        YAML::Node tag(YAML::NodeType::Scalar);
        tag.SetTag(context.getTag(prop.enclosingMetaObject()->className(), prop.name(), obj).toStdString());
        node[prop.name()] = tag;
        continue;
      } else if (! context.contains(obj)) {
        errMsg(err) << "Cannot reference object of type " << obj->metaObject()->className()
                    << " object not labeled.";
        return false;
      }
      node[prop.name()] = context.getId(obj).toStdString();
    } else if (ConfigObjectRefList *refs = prop.read(this).value<ConfigObjectRefList *>()) {
      //logDebug() << "Serialize obj ref list w/ " << refs->count() << " elements." ;
      YAML::Node list = YAML::Node(YAML::NodeType::Sequence);
      list.SetStyle(YAML::EmitterStyle::Flow);
      for (int i=0; i<refs->count(); i++) {
        ConfigObject *obj = refs->get(i);
        if (context.hasTag(prop.enclosingMetaObject()->className(), prop.name(), obj)) {
          YAML::Node tag(YAML::NodeType::Scalar);
          tag.SetTag(context.getTag(prop.enclosingMetaObject()->className(), prop.name(), obj).toStdString());
          //tag = tag.Tag().substr(1);
          list.push_back(tag);
          continue;
        } else if (! context.contains(obj)) {
          errMsg(err) << "Cannot reference object of type " << obj->metaObject()->className()
                      << " object not labeled.";
          return false;
        }
        list.push_back(context.getId(obj).toStdString());
      }
      node[prop.name()] = list;
    } else if (propIsInstance<ConfigItem>(prop)) {
      ConfigItem *obj = prop.read(this).value<ConfigItem *>();
      // Serialize config objects in-place.
      if (obj)
        node[prop.name()] = obj->serialize(context);
    } else if (ConfigObjectList *lst = prop.read(this).value<ConfigObjectList *>()) {
      // Serialize config object lists in-place.
      node[prop.name()] = lst->serialize(context);
    } else {
      logDebug() << "Unhandled property " << prop.name()
                 << " of unknown type " << prop.typeName() << ".";
    }
  }

  return true;
}

ConfigItem *
ConfigItem::allocateChild(QMetaProperty &prop, const YAML::Node &node, const Context &ctx, const ErrorStack &err) {
  Q_UNUSED(node); Q_UNUSED(ctx);

  if (QMetaType::UnknownType == prop.userType()) {
    errMsg(err) << "Cannot instantiate child of unregistered type " << prop.typeName() << ".";
    return nullptr;
  }

  QMetaType type(prop.userType());
  if (! (QMetaType::PointerToQObject & type.flags())) {
    errMsg(err) << "Cannot instantiate child of non-qobject pointer type " << prop.typeName() << ".";
    return nullptr;
  }

  const QMetaObject *propType = type.metaObject();
  /*logDebug() << "Try to instantiate child of type " << prop.typeName()
             << " for element " << prop.name()
             << " in " << this->metaObject()->className() << ".";*/

  ConfigItem *item = qobject_cast<ConfigItem *>(
        propType->newInstance(Q_ARG(QObject *,this)));
  if (! item) {
    errMsg(err) << "Could not instantiate " << propType->className() << ".";
  }
  return item;
}

bool
ConfigItem::parse(const YAML::Node &node, ConfigItem::Context &ctx, const ErrorStack &err) {
  Q_UNUSED(ctx)

  if (! node)
    return false;

  if (! node.IsMap()) {
    errMsg(err) << node.Mark().line << ":" << node.Mark().column
                << ": Cannot parse element: Expected object.";
    return false;
  }

  const QMetaObject *meta = this->metaObject();
  for (int p=QObject::staticMetaObject.propertyOffset(); p<meta->propertyCount(); p++) {
    QMetaProperty prop = meta->property(p);

    if (! prop.isValid())
      continue;
    // If marked as non-scriptable, skip that property.
    // It is handled separately or not at all.
    if (! prop.isScriptable())
      continue;

    /// @todo With Qt 5.15, we can use the REQUIRED flag to check for mandatory properties.
    /// However, Ubuntu 20.04 (Focal) comes with Qt 5.12.

    if (prop.isEnumType()) {
      // If property is not set -> skip
      if (! node[prop.name()])
        continue;
      // parse & check enum key
      if (! node[prop.name()].IsScalar()) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Cannot parse " << prop.name() << " of " << meta->className()
                    << ": Expected enum key.";
        return false;
      }
      QMetaEnum e = prop.enumerator();
      std::string key = node[prop.name()].as<std::string>();
      bool ok=true; int value = e.keyToValue(key.c_str(), &ok);
      if (! ok) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Unknown key '" << key.c_str() << "' for enum '" << prop.name()
                    << "'. Expected one of " << enumKeys(e).join(", ") << ".";
        return false;
      }
      // finally set property
      prop.write(this, value);
    } else if (QString("bool") == prop.typeName()) {
      // If property is not set -> skip
      if (! node[prop.name()])
        continue;
      // parse & check type
      if (! node[prop.name()].IsScalar()) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Cannot parse " << prop.name() << " of " << meta->className()
                    << ": Expected boolean value.";
        return false;
      }
      prop.write(this, node[prop.name()].as<bool>());
    } else if (QString("int") == prop.typeName()) {
      // If property is not set -> skip
      if (! node[prop.name()])
        continue;
      // parse & check type
      if (! node[prop.name()].IsScalar()) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Cannot parse " << prop.name() << " of " << meta->className()
                    << ": Expected integer value.";
        return false;
      }
      prop.write(this, node[prop.name()].as<int>());
    } else if (QString("uint") == prop.typeName()) {
      // If property is not set -> skip
      if (! node[prop.name()])
        continue;
      // parse & check type
      if (! node[prop.name()].IsScalar()) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Cannot parse " << prop.name() << " of " << meta->className()
                    << ": Expected unsigned integer value.";
        return false;
      }
      prop.write(this, node[prop.name()].as<unsigned>());
    } else if (QString("double") == prop.typeName()) {
      // If property is not set -> skip
      if (! node[prop.name()])
        continue;
      // parse & check type
      if (! node[prop.name()].IsScalar()) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Cannot parse " << prop.name() << " of " << meta->className()
                    << ": Expected floating point value.";
        return false;
      }
      prop.write(this, node[prop.name()].as<double>());
    } else if (QString("QString") == prop.typeName()) {
      // If property is not set -> skip
      if (! node[prop.name()])
        continue;
      // parse & check type
      if (! node[prop.name()].IsScalar()) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Cannot parse " << prop.name() << " of " << meta->className()
                    << ": Expected string.";
        return false;
      }
      prop.write(this, QString::fromStdString(node[prop.name()].as<std::string>()));
    } else if (QString("Frequency") == prop.typeName()) {
      // If property is not set -> skip
      if (! node[prop.name()])
        continue;
      // parse & check type
      if (! node[prop.name()].IsScalar()) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Cannot parse " << prop.name() << " of " << meta->className()
                    << ": Expected frequency.";
        return false;
      }
      Frequency f = node[prop.name()].as<Frequency>();
      prop.write(this, QVariant::fromValue(f));
    } else if (QString("Interval") == prop.typeName()) {
      // If property is not set -> skip
      if (! node[prop.name()])
        continue;
      // parse & check type
      if (! node[prop.name()].IsScalar()) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Cannot parse " << prop.name() << " of " << meta->className()
                    << ": Expected interval.";
        return false;
      }
      prop.write(this, QVariant::fromValue(node[prop.name()].as<Interval>()));
    } else if (QString("SelectiveCall") == prop.typeName()) {
      // If property is not set -> skip
      if ((! node[prop.name()]) || (node[prop.name()].IsNull())) {
        prop.write(this, QVariant::fromValue(SelectiveCall()));
        continue;
      }
      // parse & check type
      if ((! node[prop.name()].IsMap()) || (1 != node[prop.name()].size())) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Cannot parse " << prop.name() << " of " << meta->className()
                    << ": Expected selective call.";
        return false;
      }
      prop.write(this, QVariant::fromValue(node[prop.name()].as<SelectiveCall>()));
    } else if (prop.read(this).value<ConfigObjectReference *>()) {
      // references are linked later
      continue;
    } else if (prop.read(this).value<ConfigObjectRefList *>()) {
      // reference lists are linked later
      continue;
    } else if (propIsInstance<ConfigItem>(prop)) {
      if (! node[prop.name()])
        continue;
      // check type
      if (! node[prop.name()].IsMap()) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Cannot parse '" << prop.name() << "' of '" << meta->className()
                    << "': Expected instance of '"
                    << QMetaType(prop.typeId()).metaObject()->className() << "'.";
        return false;
      }
      // Get object
      ConfigItem *obj = prop.read(this).value<ConfigItem*>();

      // If not set and writable -> allocate and set
      if ((nullptr == obj) && prop.isWritable()) {
        if (nullptr == (obj = this->allocateChild(prop, node[prop.name()], ctx))) {
          errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                      << ": Cannot allocate " << prop.name() << " of " << meta->className() << ".";
          return false;
        }
        // Set property
        if (! prop.write(this, QVariant::fromValue(obj))) {
          if (nullptr == obj->parent())
            obj->deleteLater();
          errMsg(err) << "Cannot set writable property '" << prop.name()
                      << "' in " << this->metaObject()->className() << ".";
          return false;
        }
      }

      // parse instance
      YAML::Node propNode = node[prop.name()];
      if (obj && (! obj->parse(propNode, ctx, err))) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Cannot parse " << prop.name() << " of " << meta->className() << ".";
        if (nullptr == obj->parent())
          obj->deleteLater();
        return false;
      }
    } else if (prop.read(this).value<ConfigObjectList *>()) {
      if (! node[prop.name()])
        continue;
      // check type
      if (! node[prop.name()].IsSequence()) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Cannot parse " << prop.name() << " of " << meta->className()
                    << ": Expected instance of '"
                    << QMetaType(prop.typeId()).metaObject()->className() << "'.";
        return false;
      }
      // Get list
      ConfigObjectList *lst = prop.read(this).value<ConfigObjectList*>();
      // If not set and writable -> allocate and set
      if ((nullptr == lst) && prop.isWritable()) {
        if (nullptr == (lst = this->allocateChild(prop, node[prop.name()], ctx)->as<ConfigObjectList>())) {
          errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                      << ": Cannot allocate list " << prop.name() << " of " << meta->className() << ".";
          return false;
        }
        // Set property
        if (! prop.write(this, QVariant::fromValue(lst))) {
          if (nullptr == lst->parent())
            lst->deleteLater();
          errMsg(err) << "Cannot set writable property '" << prop.name()
                      << "' in " << this->metaObject()->className() << ".";
          return false;
        }
      }

      // Allocate elements
      ConfigObject *obj = nullptr;
      for (YAML::const_iterator it=node[prop.name()].begin(); it!=node[prop.name()].end(); it++) {
        // allocate element
        if (nullptr == (obj = lst->allocateChild(*it, ctx, err)->as<ConfigObject>())) {
          errMsg(err) << it->Mark().line << ":" << it->Mark().column
                      << ": Cannot allocate child of list.";
          return false;
        }
        // parse element
        if (obj && (! obj->parse(*it, ctx))) {
          errMsg(err) << it->Mark().line << ":" << it->Mark().column
                      << ": Cannot parse object of type " << obj->metaObject()->className();
          if (nullptr == obj->parent())
            obj->deleteLater();
          return false;
        }
        // add element to list
        if (-1 == lst->add(obj)) {
          errMsg(err) << it->Mark().line << ":" << it->Mark().column
                      << ": Cannot add element '" << obj->name() << "' of type "
                      << obj->metaObject()->className() << "' to list.";
          if (nullptr == obj->parent())
            obj->deleteLater();
          return false;
        }
      }
    }
  }

  return true;
}

bool
ConfigItem::link(const YAML::Node &node, const ConfigItem::Context &ctx, const ErrorStack &err) {
  Q_UNUSED(ctx)

  const QMetaObject *meta = this->metaObject();

  for (int p=QObject::staticMetaObject.propertyOffset(); p<meta->propertyCount(); p++) {
    QMetaProperty prop = meta->property(p);
    if (! prop.isValid())
      continue;

    if (! prop.isScriptable()) {
      //logDebug() << "Do not link property '" << prop.name() << "': Marked as not scriptable.";
      continue;
    }
    if ((prop.isEnumType()) || (QString("bool") == prop.typeName()) || (QString("int") == prop.typeName()) ||
        (QString("uint") == prop.typeName()) || (QString("double") == prop.typeName()) || (QString("QString") == prop.typeName()) ) {
      continue;
    } else if (ConfigObjectReference *ref = prop.read(this).value<ConfigObjectReference *>()) {
      // If not set -> skip
      if (! node[prop.name()])
        continue;
      // check type
      if (! node[prop.name()].IsScalar()) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Cannot link " << prop.name() << " of " << meta->className()
                    << ": Expected id.";
        return false;
      }
      // handle tags
      QString tag = QString::fromStdString(node[prop.name()].Tag());
      if ((!node[prop.name()].Scalar().size()) && (!tag.isEmpty())) {
        if (! ref->set(ctx.getTag(prop.enclosingMetaObject()->className(), prop.name(), tag))) {
          errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                      << ": Cannot link " << prop.name() << " of " << meta->className()
                      << ": Unknown tag " << tag << ".";
          return false;
        }
        continue;
      }
      // set reference
      QString id = QString::fromStdString(node[prop.name()].as<std::string>());
      if (! ctx.contains(id)) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Cannot link reference to '" << id << "', element not defined.";
        return false;
      }
      if (! ref->set(ctx.getObj(id))) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Cannot link " << prop.name() << " of " << meta->className()
                    << ": Cannot set reference.";
        return false;
      }
      /*logDebug() << "Linked reference " << prop.name() << "='" << id
                 << "' to " << ctx.getObj(id)->metaObject()->className()
                 << " '" << ctx.getObj(id)->name() << "'.";*/
    } else if (ConfigObjectRefList *lst = prop.read(this).value<ConfigObjectRefList *>()) {
      // If not set -> skip
      if (! node[prop.name()])
        continue;
      // check type
      if (! node[prop.name()].IsSequence()) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Cannot link " << prop.name() << " of " << meta->className()
                    << ": Expected sequence.";
        return false;
      }
      for (YAML::const_iterator it=node[prop.name()].begin(); it!=node[prop.name()].end(); it++) {
        if (! it->IsScalar()) {
          errMsg(err) << it->Mark().line << ":" << it->Mark().column
                      << ": Cannot link " << prop.name() << " of " << meta->className()
                      << ": Expected ID string.";
          return false;
        }
        // check for tags
        QString tag = QString::fromStdString(it->Tag());
        if ((!it->Scalar().size()) && (!tag.isEmpty())) {
          if (0 > lst->add(ctx.getTag(prop.enclosingMetaObject()->className(), prop.name(), tag))) {
            errMsg(err) << it->Mark().line << ":" << it->Mark().column
                        << ": Cannot link " << prop.name() << " of " << meta->className()
                        << ": Cannot add reference for tag '" << tag << "'.";
            return false;
          }
          continue;
        }
        QString id = QString::fromStdString(it->as<std::string>());
        if (! ctx.contains(id)) {
          errMsg(err) << it->Mark().line << ":" << it->Mark().column
                      << ": Cannot link " << prop.name() << " of " << meta->className()
                      << ": Reference '" << id << "' not defined.";
          return false;
        }
        if (0 > lst->add(ctx.getObj(id))) {
          errMsg(err) << it->Mark().line << ":" << it->Mark().column
                      << ": Cannot link " << prop.name() << " of " << meta->className()
                      << ": Cannot add reference to '" << id << "' to list.";
          return false;
        }
      }

    } else if (ConfigItem *obj = prop.read(this).value<ConfigItem *>()) {
      // If not set -> skip
      if (! node[prop.name()])
        continue;

      // check type
      if (! node[prop.name()].IsMap()) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Cannot link " << prop.name() << " of " << meta->className()
                    << ": Expected object.";
        return false;
      }

      if (! obj->link(node[prop.name()], ctx, err)) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Cannot link " << prop.name() << " of " << meta->className() << ".";
        return false;
      }
    } else if (ConfigObjectList *lst = prop.read(this).value<ConfigObjectList *>()) {
      // If not set -> skip
      if (! node[prop.name()])
        continue;

      // check type
      if (! node[prop.name()].IsSequence()) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Cannot link " << prop.name() << " of " << meta->className()
                    << ": Expected sequence.";
        return false;
      }

      if (! lst->link(node[prop.name()], ctx, err)) {
        errMsg(err) << node[prop.name()].Mark().line << ":" << node[prop.name()].Mark().column
                    << ": Cannot link " << prop.name() << " of " << meta->className() << ".";
        return false;
      }
    }
  }

  return true;
}

const Config *
ConfigItem::config() const {
  if (nullptr == parent())
    return nullptr;
  if (ConfigItem *item = qobject_cast<ConfigItem*>(parent()))
    return item->config();
  if (ConfigObjectList *lst = qobject_cast<ConfigObjectList*>(parent()))
    return lst->config();
  return nullptr;
}

void
ConfigItem::findItemsOfTypes(const QStringList &typeNames, QSet<ConfigItem *> &items) const {
  // Do not check yourself
  const QMetaObject *meta = metaObject();

  // Visit all properties
  for (int p=QObject::staticMetaObject.propertyCount(); p<meta->propertyCount(); p++) {
    QMetaProperty prop = meta->property(p);
    if (! prop.isValid())
      continue;
    if (! prop.isReadable())
      continue;

    if (ConfigItem *obj = prop.read(this).value<ConfigItem *>()) {
      if (isInstanceOf(obj, typeNames))
        items.insert(obj);
      obj->findItemsOfTypes(typeNames, items);
    } else if (ConfigObjectList *lst = prop.read(this).value<ConfigObjectList *>()) {
      lst->findItemsOfTypes(typeNames, items);
    }
  }
}

bool
ConfigItem::hasDescription() const {
  const QMetaObject *meta = metaObject();
  return (0 <= meta->indexOfClassInfo("description"));
}

bool
ConfigItem::hasLongDescription() const {
  const QMetaObject *meta = metaObject();
  return (0 <= meta->indexOfClassInfo("longDescription"));
}

bool
ConfigItem::hasDescription(const QMetaProperty &prop) const {
  if (! prop.isValid())
    return false;
  QString infoName = QString("%1Description").arg(prop.name());
  const QMetaObject *meta = metaObject();
  return (0 <= meta->indexOfClassInfo(infoName.toLocal8Bit().constData()));
}

bool
ConfigItem::hasLongDescription(const QMetaProperty &prop) const {
  if (! prop.isValid())
    return false;
  QString infoName = QString("%1LongDescription").arg(prop.name());
  const QMetaObject *meta = metaObject();
  return (0 <= meta->indexOfClassInfo(infoName.toLocal8Bit().constData()));
}

QString
ConfigItem::description() const {
  if (! hasDescription())
    return metaObject()->className();
  const QMetaObject *meta = metaObject();
  return meta->classInfo(meta->indexOfClassInfo("description")).value();
}

QString
ConfigItem::longDescription() const {
  if (! hasLongDescription())
    return QString();
  const QMetaObject *meta = metaObject();
  return meta->classInfo(meta->indexOfClassInfo("longDescription")).value();
}

QString
ConfigItem::description(const QMetaProperty &prop) const {
  if (! hasDescription(prop))
    return QString();
  QString infoName = QString("%1Description").arg(prop.name());
  const QMetaObject *meta = metaObject();
  return meta->classInfo(meta->indexOfClassInfo(infoName.toLocal8Bit().constData())).value();
}

QString
ConfigItem::longDescription(const QMetaProperty &prop) const {
  if (! hasLongDescription(prop))
    return QString();
  QString infoName = QString("%1LongDescription").arg(prop.name());
  const QMetaObject *meta = metaObject();
  return meta->classInfo(meta->indexOfClassInfo(infoName.toLocal8Bit().constData())).value();
}


/* ********************************************************************************************* *
 * Implementation of ConfigObject
 * ********************************************************************************************* */
ConfigObject::ConfigObject(QObject *parent)
  : ConfigItem(parent), _name()
{
  // pass...
}

ConfigObject::ConfigObject(const QString &name, QObject *parent)
  : ConfigItem(parent), _name(name)
{
  // pass...
}

const QString &
ConfigObject::name() const {
  return _name;
}

void
ConfigObject::setName(const QString &name) {
  if (name.simplified().isEmpty() || (_name == name.simplified()))
    return;
  _name = name;
  emit modified(this);
}

QString
ConfigObject::idPrefix() const {
  return findIdPrefix(this->metaObject());
}

bool
ConfigObject::label(ConfigObject::Context &context, const ErrorStack &err) {
  unsigned n=1;
  QString prefix = this->idPrefix();
  QString id=QString("%1%2").arg(prefix).arg(n);
  while (context.contains(id)) {
    id=QString("%1%2").arg(prefix).arg(++n);
  }

  if (! context.add(id, this)) {
    if (context.contains(this))
      errMsg(err) << "Object already in context with id '" << context.getId(this) << "'.";
    errMsg(err) << "Cannot add element '" << id << "' to context.";
    return false;
  }

  if (! ConfigItem::label(context, err))
    return false;

  return true;
}

bool
ConfigObject::parse(const YAML::Node &node, Context &ctx, const ErrorStack &err) {
  if (! node["id"]) {
    logWarn() << node.Mark().line << ":" << node.Mark().column
              << ": No id specified for " << metaObject()->className()
              << ". Object cannot be referenced later.";
  } else {
    QString id = QString::fromStdString(node["id"].as<std::string>());
    if (! ctx.add(id, this)) {
      errMsg(err) << node["id"].Mark().line << ":" << node["id"].Mark().column
                  << ": Cannot register ID '" << id << "'.";
      return false;
    }
  }

  return ConfigItem::parse(node, ctx);
}

bool
ConfigObject::populate(YAML::Node &node, const Context &context, const ErrorStack &err) {
  if (context.contains(this))
    node["id"] = context.getId(this).toStdString();
  return ConfigItem::populate(node, context, err);
}

QString
ConfigObject::findIdPrefix(const QMetaObject *meta) {
  for (int i=meta->classInfoOffset(); i<meta->classInfoCount(); i++) {
    if (0 == strcmp("IdPrefix", meta->classInfo(i).name())) {
      return meta->classInfo(i).value();
    }
  }
  if (meta->superClass())
    return findIdPrefix(meta->superClass());
  return "";
}


/* ********************************************************************************************* *
 * Implementation of ConfigExtension
 * ********************************************************************************************* */
ConfigExtension::ConfigExtension(QObject *parent)
  : ConfigItem(parent)
{
  // pass...
}


/* ********************************************************************************************* *
 * Implementation of AbstractConfigObjectList
 * ********************************************************************************************* */
AbstractConfigObjectList::AbstractConfigObjectList(const QMetaObject &elementType, QObject *parent)
  : QObject(parent), _elementTypes(), _items()
{
  _elementTypes.append(elementType);
}

AbstractConfigObjectList::AbstractConfigObjectList(const std::initializer_list<QMetaObject> &elementTypes, QObject *parent)
  : QObject(parent), _elementTypes(elementTypes), _items()
{
  // pass...
}

bool
AbstractConfigObjectList::copy(const AbstractConfigObjectList &other) {
  this->clear();
  _elementTypes = other._elementTypes;
  foreach (ConfigObject *item, other._items)
    add(item);
  return true;
}

int
AbstractConfigObjectList::count() const {
  return _items.count();
}

int
AbstractConfigObjectList::indexOf(ConfigObject *obj) const {
  return _items.indexOf(obj);
}

void
AbstractConfigObjectList::clear() {
  for (int i=(count()-1); i>=0; i--) {
    _items.pop_back();
    emit elementRemoved(i);
  }
}

const Config *
AbstractConfigObjectList::config() const {
  if (nullptr == parent())
    return nullptr;
  if (ConfigItem *item = qobject_cast<ConfigItem *>(parent()))
    return item->config();
  return nullptr;
}

void
AbstractConfigObjectList::findItemsOfTypes(const QStringList &typeNames, QSet<ConfigItem *> &items) const {
  foreach (ConfigObject *obj, _items) {
    if (isInstanceOf(obj, typeNames))
      items.insert(obj);
    obj->findItemsOfTypes(typeNames, items);
  }
}

QList<ConfigObject *>
AbstractConfigObjectList::findItemsByName(const QString name) const {
  QList<ConfigObject *> items;
  foreach (ConfigObject *obj, _items) {
    if (obj->name() == name)
      items.append(obj);
  }
  return items;
}

bool
AbstractConfigObjectList::has(ConfigObject *obj) const {
  return 0 <= indexOf(obj);
}

ConfigObject *
AbstractConfigObjectList::get(int idx) const {
  return _items.value(idx, nullptr);
}

int
AbstractConfigObjectList::add(ConfigObject *obj, int row, bool unique) {
  // Ignore nullptr
  if (nullptr == obj)
    return -1;
  // If already in list -> ignore
  if (unique && (0 <= indexOf(obj)))
    return -1;
  if (-1 == row)
    row = _items.size();
  // Check type
  bool matchesType = false;
  foreach (const QMetaObject &type, _elementTypes) {
    if (obj->inherits(type.className())) {
      matchesType = true;
      break;
    }
  }
  if (! matchesType) {
    logError() << "Cannot add element of type " << obj->metaObject()->className()
               << " to list, expected instances of " << classNames().join(", ");
    return -1;
  }
  _items.insert(row, obj);
  // Otherwise connect to object
  connect(obj, SIGNAL(destroyed(QObject*)), this, SLOT(onElementDeleted(QObject*)));
  connect(obj, SIGNAL(modified(ConfigItem*)), this, SLOT(onElementModified(ConfigItem*)));
  emit elementAdded(row);
  return row;
}

int
AbstractConfigObjectList::replace(ConfigObject *obj, int row, bool unique) {
  // Ignore nullptr
  if (nullptr == obj)
    return -1;
  // Check index
  if (row >= count())
    return -1;
  // Check if self-replacement
  if (row == indexOf(obj))
    return indexOf(obj);
  // If already in list -> ignore
  if (unique && (0 <= indexOf(obj)))
    return -1;
  // Check type
  bool matchesType = false;
  foreach (const QMetaObject &type, _elementTypes) {
    if (obj->inherits(type.className())) {
      matchesType = true;
      break;
    }
  }
  if (! matchesType) {
    logError() << "Cannot add element of type " << obj->metaObject()->className()
               << " to list, expected instances of " << classNames().join(", ");
    return -1;
  }

  // Remove present element
  ConfigObject *oldobj = _items.at(row);
  _items.remove(row, 1);
  emit elementRemoved(row);
  disconnect(oldobj, nullptr, this, nullptr);

  _items.insert(row, obj);
  // connect to object
  connect(obj, SIGNAL(destroyed(QObject*)), this, SLOT(onElementDeleted(QObject*)));
  connect(obj, SIGNAL(modified(ConfigItem*)), this, SLOT(onElementModified(ConfigItem*)));
  emit elementAdded(row);

  return row;
}

bool
AbstractConfigObjectList::take(ConfigObject *obj) {
  // Ignore nullptr
  if (nullptr == obj)
    return false;
  int idx = indexOf(obj);
  if (0 > idx)
    return false;
  _items.remove(idx, 1);
  emit elementRemoved(idx);
  // Otherwise disconnect from
  disconnect(obj, nullptr, this, nullptr);
  return true;
}

bool
AbstractConfigObjectList::del(ConfigObject *obj) {
  return take(obj);
}

bool
AbstractConfigObjectList::moveUp(int row) {
  if ((row <= 0) || (row>=count()))
    return false;
  std::swap(_items[row-1], _items[row]);
  return true;
}

bool
AbstractConfigObjectList::moveUp(int first, int last) {
  if ((first <= 0) || (last>=count()))
    return false;
  for (int row=first; row<=last; row++)
    std::swap(_items[row-1], _items[row]);
  return true;
}

bool
AbstractConfigObjectList::moveDown(int row) {
  if ((row >= (count()-1)) || (0 > row))
    return false;
  std::swap(_items[row+1], _items[row]);
  return true;
}

bool
AbstractConfigObjectList::moveDown(int first, int last) {
  if ((last >= (count()-1)) || (0 > first))
    return false;
  for (int row=last; row>=first; row--)
    std::swap(_items[row+1], _items[row]);
  return true;
}


bool
AbstractConfigObjectList::move(int source, int count, int destination) {
  if ((0 == count) || (source == destination))
    return true;

  if ((source+count)>_items.size())
    return false;

  if (source > destination) {
    // move up
    for (int take=source, put=destination, i=0; i<count; i++, take++, put++)
      _items.insert(put, _items.takeAt(take));
  } else {
    // move down
    for (int i=0; i<count; i++)
      _items.insert(destination-1, _items.takeAt(source));
  }

  for (int i=0; i<count; i++)
    emit elementModified(destination+i);

  return true;
}


const QList<QMetaObject> &
AbstractConfigObjectList::elementTypes() const {
  return _elementTypes;
}

QStringList
AbstractConfigObjectList::classNames() const {
  QStringList cls;
  foreach (const QMetaObject &type, _elementTypes) {
    cls.append(type.className());
  }
  return cls;
}

void
AbstractConfigObjectList::onElementModified(ConfigItem *obj) {
  int idx = indexOf(obj->as<ConfigObject>());
  if (0 <= idx)
    emit elementModified(idx);
}

void
AbstractConfigObjectList::onElementDeleted(QObject *obj) {
  // Use reinterpret cast here as the obj may already be destroyed and this all RTTI freed.
  // We just use the pointer address to remove the element here.
  int idx = indexOf(reinterpret_cast<ConfigObject *>(obj));
  if (0 <= idx) {
    _items.remove(idx);
    emit elementRemoved(idx);
  }
}


/* ********************************************************************************************* *
 * Implementation of ConfigObjectList
 * ********************************************************************************************* */
ConfigObjectList::ConfigObjectList(const QMetaObject &elementType, QObject *parent)
  : AbstractConfigObjectList(elementType, parent)
{
  // pass...
}

ConfigObjectList::ConfigObjectList(const std::initializer_list<QMetaObject> &elementTypes, QObject *parent)
  : AbstractConfigObjectList(elementTypes, parent)
{
  // pass...
}

bool
ConfigObjectList::label(ConfigItem::Context &context, const ErrorStack &err) {
  foreach (ConfigItem *obj, _items) {
    if (! obj->label(context, err))
      return false;
  }
  return true;
}

YAML::Node
ConfigObjectList::serialize(const ConfigItem::Context &context, const ErrorStack &err) {
  YAML::Node list(YAML::NodeType::Sequence);
  foreach (ConfigItem *obj, _items) {
    YAML::Node node = obj->serialize(context, err);
    if (node.IsNull())
      return node;
    list.push_back(node);
  }
  return list;
}

bool
ConfigObjectList::parse(const YAML::Node &node, ConfigItem::Context &ctx, const ErrorStack &err) {
  if (! node)
    return false;

  if (!node.IsSequence()) {
    errMsg(err) << node.Mark().line << ":" << node.Mark().column
                << ": Cannot parse list: Expected list.";
    return false;
  }

  for (YAML::Node::const_iterator it=node.begin(); it!=node.end(); it++) {
    // Create object for node
    ConfigItem *element = allocateChild(*it, ctx);
    if ((nullptr == element) || (!element->is<ConfigObject>())) {
      errMsg(err) << it->Mark().line << ":" << it->Mark().column << ": Cannot parse list.";
      return false;
    }
    if (! element->parse(*it, ctx, err)) {
      errMsg(err) << it->Mark().line << ":" << it->Mark().column << ": Cannot parse list.";
      element->deleteLater();
      return false;
    }
    if (0 > add(element->as<ConfigObject>())) {
      errMsg(err) << it->Mark().line << ":" << it->Mark().column
                  << ": Cannot add element to list.";
      element->deleteLater();
      return false;
    }
  }

  return true;
}

bool
ConfigObjectList::link(const YAML::Node &node, const ConfigItem::Context &ctx, const ErrorStack &err) {
  if (! node)
    return false;

  if (!node.IsSequence()) {
    errMsg(err) << node.Mark().line << ":" << node.Mark().column
                << ": Cannot parse list: Expected list.";
    return false;
  }
  int i = 0;
  YAML::Node::const_iterator it=node.begin();
  for (; it!=node.end(); it++, i++) {
    // Create object for node
    ConfigItem *element = get(i);
    if (nullptr == element) {
      errMsg(err) << it->Mark().line << ":" << it->Mark().column
                  << ": Cannot link list, " << i << "-th element not present.";
      return false;
    }
    if (! element->link(*it, ctx, err)) {
      errMsg(err) << it->Mark().line << ":" << it->Mark().column
                  << ": Cannot link list.";
      return false;
    }
  }

  return true;
}

int ConfigObjectList::add(ConfigObject *obj, int row, bool unique) {
  if (0 <= (row = AbstractConfigObjectList::add(obj, row, unique)))
    obj->setParent(this);
  return row;
}

bool
ConfigObjectList::take(ConfigObject *obj) {
  if (AbstractConfigObjectList::take(obj))
    obj->setParent(nullptr);
  return true;
}

bool
ConfigObjectList::del(ConfigObject *obj) {
  if (AbstractConfigObjectList::del(obj))
    delete obj;
  return true;
}

void
ConfigObjectList::clear() {
  QVector<ConfigObject *> items = _items;
  AbstractConfigObjectList::clear();
  for (int i=0; i<items.count(); i++)
    items[i]->deleteLater();
}

bool
ConfigObjectList::copy(const AbstractConfigObjectList &other) {
  clear();
  _elementTypes = other.elementTypes();
  for (int i=0; i<other.count(); i++)
    add(other.get(i)->clone()->as<ConfigObject>());
  return true;
}

int
ConfigObjectList::compare(const ConfigObjectList &other) const {
  if (count() < other.count())
    return -1;
  if (count() > other.count())
    return 1;
  for (int i=0; i<count(); i++) {
    int cmp = this->get(i)->compare(*other.get(i));
    if (cmp) return cmp;
  }

  return 0;
}

/* ********************************************************************************************* *
 * Implementation of ConfigObjectRefList
 * ********************************************************************************************* */
ConfigObjectRefList::ConfigObjectRefList(const QMetaObject &elementType, QObject *parent)
  : AbstractConfigObjectList(elementType, parent)
{
  // pass...
}

ConfigObjectRefList::ConfigObjectRefList(const std::initializer_list<QMetaObject> &elementTypes, QObject *parent)
  : AbstractConfigObjectList(elementTypes, parent)
{
  // pass...
}

bool
ConfigObjectRefList::label(ConfigItem::Context &context, const ErrorStack &err) {
  Q_UNUSED(context); Q_UNUSED(err);
  // pass...
  return true;
}

YAML::Node
ConfigObjectRefList::serialize(const ConfigItem::Context &context, const ErrorStack &err) {
  YAML::Node list(YAML::NodeType::Sequence);
  foreach (ConfigObject *obj, _items) {
    if (! context.contains(obj)) {
      errMsg(err) << "Cannot serialized ref list: Object '" << obj->name() << "' not in context!";
      return YAML::Node();
    }
    list.push_back(context.getId(obj).toStdString());
  }
  return list;
}

int
ConfigObjectRefList::compare(const ConfigObjectRefList &other) const {
  if (count() < other.count()) return -1;
  if (count() > other.count()) return 1;
  for (int i=0; i<count(); i++) {
    int cmp = get(i)->compare(*other.get(i));
    if (cmp) return cmp;
  }
  return 0;
}