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

#include "JSONServiceDescription.h"

#include "AddonsOperations.h"
#include "ApplicationOperations.h"
#include "AudioLibrary.h"
#include "FavouritesOperations.h"
#include "FileOperations.h"
#include "GUIOperations.h"
#include "InputOperations.h"
#include "JSONRPC.h"
#include "PVROperations.h"
#include "PlayerOperations.h"
#include "PlaylistOperations.h"
#include "ProfilesOperations.h"
#include "ServiceDescription.h"
#include "SettingsOperations.h"
#include "SystemOperations.h"
#include "TextureOperations.h"
#include "VideoLibrary.h"
#include "XBMCOperations.h"
#include "utils/JSONVariantParser.h"
#include "utils/StringUtils.h"
#include "utils/log.h"

using namespace JSONRPC;

std::map<std::string, CVariant> CJSONServiceDescription::m_notifications = std::map<std::string, CVariant>();
CJSONServiceDescription::CJsonRpcMethodMap CJSONServiceDescription::m_actionMap;
std::map<std::string, JSONSchemaTypeDefinitionPtr> CJSONServiceDescription::m_types = std::map<std::string, JSONSchemaTypeDefinitionPtr>();
CJSONServiceDescription::IncompleteSchemaDefinitionMap CJSONServiceDescription::m_incompleteDefinitions = CJSONServiceDescription::IncompleteSchemaDefinitionMap();

// clang-format off

JsonRpcMethodMap CJSONServiceDescription::m_methodMaps[] = {
// JSON-RPC
  { "JSONRPC.Introspect",                           CJSONRPC::Introspect },
  { "JSONRPC.Version",                              CJSONRPC::Version },
  { "JSONRPC.Permission",                           CJSONRPC::Permission },
  { "JSONRPC.Ping",                                 CJSONRPC::Ping },
  { "JSONRPC.GetConfiguration",                     CJSONRPC::GetConfiguration },
  { "JSONRPC.SetConfiguration",                     CJSONRPC::SetConfiguration },
  { "JSONRPC.NotifyAll",                            CJSONRPC::NotifyAll },

// Player
  { "Player.GetActivePlayers",                      CPlayerOperations::GetActivePlayers },
  { "Player.GetPlayers",                            CPlayerOperations::GetPlayers },
  { "Player.GetProperties",                         CPlayerOperations::GetProperties },
  { "Player.GetItem",                               CPlayerOperations::GetItem },

  { "Player.PlayPause",                             CPlayerOperations::PlayPause },
  { "Player.Stop",                                  CPlayerOperations::Stop },
  { "Player.GetAudioDelay",                         CPlayerOperations::GetAudioDelay },
  { "Player.SetAudioDelay",                         CPlayerOperations::SetAudioDelay },
  { "Player.SetSpeed",                              CPlayerOperations::SetSpeed },
  { "Player.Seek",                                  CPlayerOperations::Seek },
  { "Player.Move",                                  CPlayerOperations::Move },
  { "Player.Zoom",                                  CPlayerOperations::Zoom },
  { "Player.SetViewMode",                           CPlayerOperations::SetViewMode },
  { "Player.GetViewMode",                           CPlayerOperations::GetViewMode },
  { "Player.Rotate",                                CPlayerOperations::Rotate },

  { "Player.Open",                                  CPlayerOperations::Open },
  { "Player.GoTo",                                  CPlayerOperations::GoTo },
  { "Player.SetShuffle",                            CPlayerOperations::SetShuffle },
  { "Player.SetRepeat",                             CPlayerOperations::SetRepeat },
  { "Player.SetPartymode",                          CPlayerOperations::SetPartymode },

  { "Player.SetAudioStream",                        CPlayerOperations::SetAudioStream },
  { "Player.AddSubtitle",                           CPlayerOperations::AddSubtitle },
  { "Player.SetSubtitle",                           CPlayerOperations::SetSubtitle },
  { "Player.SetVideoStream",                        CPlayerOperations::SetVideoStream },

// Playlist
  { "Playlist.GetPlaylists",                        CPlaylistOperations::GetPlaylists },
  { "Playlist.GetProperties",                       CPlaylistOperations::GetProperties },
  { "Playlist.GetItems",                            CPlaylistOperations::GetItems },
  { "Playlist.Add",                                 CPlaylistOperations::Add },
  { "Playlist.Insert",                              CPlaylistOperations::Insert },
  { "Playlist.Clear",                               CPlaylistOperations::Clear },
  { "Playlist.Remove",                              CPlaylistOperations::Remove },
  { "Playlist.Swap",                                CPlaylistOperations::Swap },

// Files
  { "Files.GetSources",                             CFileOperations::GetRootDirectory },
  { "Files.GetDirectory",                           CFileOperations::GetDirectory },
  { "Files.GetFileDetails",                         CFileOperations::GetFileDetails },
  { "Files.SetFileDetails",                         CFileOperations::SetFileDetails },
  { "Files.PrepareDownload",                        CFileOperations::PrepareDownload },
  { "Files.Download",                               CFileOperations::Download },

// Music Library
  { "AudioLibrary.GetProperties",                   CAudioLibrary::GetProperties },
  { "AudioLibrary.GetArtists",                      CAudioLibrary::GetArtists },
  { "AudioLibrary.GetArtistDetails",                CAudioLibrary::GetArtistDetails },
  { "AudioLibrary.GetAlbums",                       CAudioLibrary::GetAlbums },
  { "AudioLibrary.GetAlbumDetails",                 CAudioLibrary::GetAlbumDetails },
  { "AudioLibrary.GetSongs",                        CAudioLibrary::GetSongs },
  { "AudioLibrary.GetSongDetails",                  CAudioLibrary::GetSongDetails },
  { "AudioLibrary.GetRecentlyAddedAlbums",          CAudioLibrary::GetRecentlyAddedAlbums },
  { "AudioLibrary.GetRecentlyAddedSongs",           CAudioLibrary::GetRecentlyAddedSongs },
  { "AudioLibrary.GetRecentlyPlayedAlbums",         CAudioLibrary::GetRecentlyPlayedAlbums },
  { "AudioLibrary.GetRecentlyPlayedSongs",          CAudioLibrary::GetRecentlyPlayedSongs },
  { "AudioLibrary.GetGenres",                       CAudioLibrary::GetGenres },
  { "AudioLibrary.GetRoles",                        CAudioLibrary::GetRoles },
  { "AudioLibrary.GetSources",                      CAudioLibrary::GetSources },
  { "AudioLibrary.GetAvailableArtTypes",            CAudioLibrary::GetAvailableArtTypes },
  { "AudioLibrary.GetAvailableArt",                 CAudioLibrary::GetAvailableArt },
  { "AudioLibrary.SetArtistDetails",                CAudioLibrary::SetArtistDetails },
  { "AudioLibrary.SetAlbumDetails",                 CAudioLibrary::SetAlbumDetails },
  { "AudioLibrary.SetSongDetails",                  CAudioLibrary::SetSongDetails },
  { "AudioLibrary.Scan",                            CAudioLibrary::Scan },
  { "AudioLibrary.Export",                          CAudioLibrary::Export },
  { "AudioLibrary.Clean",                           CAudioLibrary::Clean },

// Video Library
  { "VideoLibrary.GetGenres",                       CVideoLibrary::GetGenres },
  { "VideoLibrary.GetTags",                         CVideoLibrary::GetTags },
  { "VideoLibrary.GetAvailableArtTypes",            CVideoLibrary::GetAvailableArtTypes },
  { "VideoLibrary.GetAvailableArt",                 CVideoLibrary::GetAvailableArt },
  { "VideoLibrary.GetMovies",                       CVideoLibrary::GetMovies },
  { "VideoLibrary.GetMovieDetails",                 CVideoLibrary::GetMovieDetails },
  { "VideoLibrary.GetMovieSets",                    CVideoLibrary::GetMovieSets },
  { "VideoLibrary.GetMovieSetDetails",              CVideoLibrary::GetMovieSetDetails },
  { "VideoLibrary.GetTVShows",                      CVideoLibrary::GetTVShows },
  { "VideoLibrary.GetTVShowDetails",                CVideoLibrary::GetTVShowDetails },
  { "VideoLibrary.GetSeasons",                      CVideoLibrary::GetSeasons },
  { "VideoLibrary.GetSeasonDetails",                CVideoLibrary::GetSeasonDetails },
  { "VideoLibrary.GetEpisodes",                     CVideoLibrary::GetEpisodes },
  { "VideoLibrary.GetEpisodeDetails",               CVideoLibrary::GetEpisodeDetails },
  { "VideoLibrary.GetMusicVideos",                  CVideoLibrary::GetMusicVideos },
  { "VideoLibrary.GetMusicVideoDetails",            CVideoLibrary::GetMusicVideoDetails },
  { "VideoLibrary.GetRecentlyAddedMovies",          CVideoLibrary::GetRecentlyAddedMovies },
  { "VideoLibrary.GetRecentlyAddedEpisodes",        CVideoLibrary::GetRecentlyAddedEpisodes },
  { "VideoLibrary.GetRecentlyAddedMusicVideos",     CVideoLibrary::GetRecentlyAddedMusicVideos },
  { "VideoLibrary.GetInProgressTVShows",            CVideoLibrary::GetInProgressTVShows },
  { "VideoLibrary.SetMovieDetails",                 CVideoLibrary::SetMovieDetails },
  { "VideoLibrary.SetMovieSetDetails",              CVideoLibrary::SetMovieSetDetails },
  { "VideoLibrary.SetTVShowDetails",                CVideoLibrary::SetTVShowDetails },
  { "VideoLibrary.SetSeasonDetails",                CVideoLibrary::SetSeasonDetails },
  { "VideoLibrary.SetEpisodeDetails",               CVideoLibrary::SetEpisodeDetails },
  { "VideoLibrary.SetMusicVideoDetails",            CVideoLibrary::SetMusicVideoDetails },
  { "VideoLibrary.RefreshMovie",                    CVideoLibrary::RefreshMovie },
  { "VideoLibrary.RefreshTVShow",                   CVideoLibrary::RefreshTVShow },
  { "VideoLibrary.RefreshEpisode",                  CVideoLibrary::RefreshEpisode },
  { "VideoLibrary.RefreshMusicVideo",               CVideoLibrary::RefreshMusicVideo },
  { "VideoLibrary.RemoveMovie",                     CVideoLibrary::RemoveMovie },
  { "VideoLibrary.RemoveTVShow",                    CVideoLibrary::RemoveTVShow },
  { "VideoLibrary.RemoveEpisode",                   CVideoLibrary::RemoveEpisode },
  { "VideoLibrary.RemoveMusicVideo",                CVideoLibrary::RemoveMusicVideo },
  { "VideoLibrary.Scan",                            CVideoLibrary::Scan },
  { "VideoLibrary.Export",                          CVideoLibrary::Export },
  { "VideoLibrary.Clean",                           CVideoLibrary::Clean },

// Addon operations
  { "Addons.GetAddons",                             CAddonsOperations::GetAddons },
  { "Addons.GetAddonDetails",                       CAddonsOperations::GetAddonDetails },
  { "Addons.SetAddonEnabled",                       CAddonsOperations::SetAddonEnabled },
  { "Addons.ExecuteAddon",                          CAddonsOperations::ExecuteAddon },

// GUI operations
  { "GUI.GetProperties",                            CGUIOperations::GetProperties },
  { "GUI.ActivateWindow",                           CGUIOperations::ActivateWindow },
  { "GUI.ShowNotification",                         CGUIOperations::ShowNotification },
  { "GUI.SetFullscreen",                            CGUIOperations::SetFullscreen },
  { "GUI.SetStereoscopicMode",                      CGUIOperations::SetStereoscopicMode },
  { "GUI.GetStereoscopicModes",                     CGUIOperations::GetStereoscopicModes },

// PVR operations
  { "PVR.GetProperties",                            CPVROperations::GetProperties },
  { "PVR.GetChannelGroups",                         CPVROperations::GetChannelGroups },
  { "PVR.GetChannelGroupDetails",                   CPVROperations::GetChannelGroupDetails },
  { "PVR.GetChannels",                              CPVROperations::GetChannels },
  { "PVR.GetChannelDetails",                        CPVROperations::GetChannelDetails },
  { "PVR.GetClients",                               CPVROperations::GetClients },
  { "PVR.GetBroadcasts",                            CPVROperations::GetBroadcasts },
  { "PVR.GetBroadcastDetails",                      CPVROperations::GetBroadcastDetails },
  { "PVR.GetBroadcastIsPlayable",                   CPVROperations::GetBroadcastIsPlayable },
  { "PVR.GetTimers",                                CPVROperations::GetTimers },
  { "PVR.GetTimerDetails",                          CPVROperations::GetTimerDetails },
  { "PVR.GetRecordings",                            CPVROperations::GetRecordings },
  { "PVR.GetRecordingDetails",                      CPVROperations::GetRecordingDetails },
  { "PVR.AddTimer",                                 CPVROperations::AddTimer },
  { "PVR.DeleteTimer",                              CPVROperations::DeleteTimer },
  { "PVR.ToggleTimer",                              CPVROperations::ToggleTimer },
  { "PVR.Record",                                   CPVROperations::Record },
  { "PVR.Scan",                                     CPVROperations::Scan },

// Profiles operations
  { "Profiles.GetProfiles",                         CProfilesOperations::GetProfiles},
  { "Profiles.GetCurrentProfile",                   CProfilesOperations::GetCurrentProfile},
  { "Profiles.LoadProfile",                         CProfilesOperations::LoadProfile},

// System operations
  { "System.GetProperties",                         CSystemOperations::GetProperties },
  { "System.EjectOpticalDrive",                     CSystemOperations::EjectOpticalDrive },
  { "System.Shutdown",                              CSystemOperations::Shutdown },
  { "System.Suspend",                               CSystemOperations::Suspend },
  { "System.Hibernate",                             CSystemOperations::Hibernate },
  { "System.Reboot",                                CSystemOperations::Reboot },

// Input operations
  { "Input.SendText",                               CInputOperations::SendText },
  { "Input.ExecuteAction",                          CInputOperations::ExecuteAction },
  { "Input.ButtonEvent",                            CInputOperations::ButtonEvent },
  { "Input.Left",                                   CInputOperations::Left },
  { "Input.Right",                                  CInputOperations::Right },
  { "Input.Down",                                   CInputOperations::Down },
  { "Input.Up",                                     CInputOperations::Up },
  { "Input.Select",                                 CInputOperations::Select },
  { "Input.Back",                                   CInputOperations::Back },
  { "Input.ContextMenu",                            CInputOperations::ContextMenu },
  { "Input.Info",                                   CInputOperations::Info },
  { "Input.Home",                                   CInputOperations::Home },
  { "Input.ShowCodec",                              CInputOperations::ShowCodec },
  { "Input.ShowOSD",                                CInputOperations::ShowOSD },
  { "Input.ShowPlayerProcessInfo",                  CInputOperations::ShowPlayerProcessInfo },

// Application operations
  { "Application.GetProperties",                    CApplicationOperations::GetProperties },
  { "Application.SetVolume",                        CApplicationOperations::SetVolume },
  { "Application.SetMute",                          CApplicationOperations::SetMute },
  { "Application.Quit",                             CApplicationOperations::Quit },

// Favourites operations
  { "Favourites.GetFavourites",                     CFavouritesOperations::GetFavourites },
  { "Favourites.AddFavourite",                      CFavouritesOperations::AddFavourite },

// Textures operations
  { "Textures.GetTextures",                         CTextureOperations::GetTextures },
  { "Textures.RemoveTexture",                       CTextureOperations::RemoveTexture },

// Settings operations
  { "Settings.GetSections",                         CSettingsOperations::GetSections },
  { "Settings.GetCategories",                       CSettingsOperations::GetCategories },
  { "Settings.GetSettings",                         CSettingsOperations::GetSettings },
  { "Settings.GetSettingValue",                     CSettingsOperations::GetSettingValue },
  { "Settings.SetSettingValue",                     CSettingsOperations::SetSettingValue },
  { "Settings.ResetSettingValue",                   CSettingsOperations::ResetSettingValue },
  { "Settings.GetSkinSettings",                     CSettingsOperations::GetSkinSettings },
  { "Settings.GetSkinSettingValue",                 CSettingsOperations::GetSkinSettingValue },
  { "Settings.SetSkinSettingValue",                 CSettingsOperations::SetSkinSettingValue },

// XBMC operations
  { "XBMC.GetInfoLabels",                           CXBMCOperations::GetInfoLabels },
  { "XBMC.GetInfoBooleans",                         CXBMCOperations::GetInfoBooleans }
};

// clang-format on

JSONSchemaTypeDefinition::JSONSchemaTypeDefinition()
  : missingReference(),
    name(),
    ID(),
    referencedType(nullptr),
    extends(),
    description(),
    unionTypes(),
    defaultValue(),
    minimum(-std::numeric_limits<double>::max()),
    maximum(std::numeric_limits<double>::max()),
    enums(),
    items(),
    additionalItems(),
    properties(),
    additionalProperties(nullptr)
{ }

bool JSONSchemaTypeDefinition::Parse(const CVariant &value, bool isParameter /* = false */)
{
  bool hasReference = false;

  // Check if the type of the parameter defines a json reference
  // to a type defined somewhere else
  if (value.isMember("$ref") && value["$ref"].isString())
  {
    // Get the name of the referenced type
    std::string refType = value["$ref"].asString();
    // Check if the referenced type exists
    JSONSchemaTypeDefinitionPtr referencedTypeDef = CJSONServiceDescription::GetType(refType);
    if (refType.length() <= 0 || referencedTypeDef.get() == NULL)
    {
      CLog::Log(LOGDEBUG, "JSONRPC: JSON schema type {} references an unknown type {}", name,
                refType);
      missingReference = refType;
      return false;
    }

    std::string typeName = name;
    *this = *referencedTypeDef;
    if (!typeName.empty())
      name = typeName;
    referencedType = referencedTypeDef;
    hasReference = true;
  }
  else if (value.isMember("id") && value["id"].isString())
    ID = GetString(value["id"], "");

  // Check if the "required" field has been defined
  optional = value.isMember("required") && value["required"].isBoolean() ? !value["required"].asBoolean() : true;

  // Get the "description"
  if (!hasReference || (value.isMember("description") && value["description"].isString()))
    description = GetString(value["description"], "");

  if (hasReference)
  {
    // If there is a specific default value, read it
    if (value.isMember("default") && IsType(value["default"], type))
    {
      bool ok = false;
      if (enums.size() <= 0)
        ok = true;
      // If the type has an enum definition we must make
      // sure that the default value is a valid enum value
      else
      {
        for (const auto& itr : enums)
        {
          if (value["default"] == itr)
          {
            ok = true;
            break;
          }
        }
      }

      if (ok)
        defaultValue = value["default"];
    }

    return true;
  }

  // Check whether this type extends an existing type
  if (value.isMember("extends"))
  {
    if (value["extends"].isString())
    {
      std::string extendsName = GetString(value["extends"], "");
      if (!extendsName.empty())
      {
        JSONSchemaTypeDefinitionPtr extendedTypeDef = CJSONServiceDescription::GetType(extendsName);
        if (extendedTypeDef.get() == NULL)
        {
          CLog::Log(LOGDEBUG, "JSONRPC: JSON schema type {} extends an unknown type {}", name,
                    extendsName);
          missingReference = extendsName;
          return false;
        }

        type = extendedTypeDef->type;
        extends.push_back(extendedTypeDef);
      }
    }
    else if (value["extends"].isArray())
    {
      JSONSchemaType extendedType = AnyValue;
      for (unsigned int extendsIndex = 0; extendsIndex < value["extends"].size(); extendsIndex++)
      {
        std::string extendsName = GetString(value["extends"][extendsIndex], "");
        if (!extendsName.empty())
        {
          JSONSchemaTypeDefinitionPtr extendedTypeDef = CJSONServiceDescription::GetType(extendsName);
          if (extendedTypeDef.get() == NULL)
          {
            extends.clear();
            CLog::Log(LOGDEBUG, "JSONRPC: JSON schema type {} extends an unknown type {}", name,
                      extendsName);
            missingReference = extendsName;
            return false;
          }

          if (extendsIndex == 0)
            extendedType = extendedTypeDef->type;
          else if (extendedType != extendedTypeDef->type)
          {
            extends.clear();
            CLog::Log(LOGDEBUG,
                      "JSONRPC: JSON schema type {} extends multiple JSON schema types of "
                      "mismatching types",
                      name);
            return false;
          }

          extends.push_back(extendedTypeDef);
        }
      }

      type = extendedType;
    }
  }

  // Only read the "type" attribute if it's
  // not an extending type
  if (extends.size() <= 0)
  {
    // Get the defined type of the parameter
    if (!CJSONServiceDescription::parseJSONSchemaType(value["type"], unionTypes, type, missingReference))
      return false;
  }

  if (HasType(type, ObjectValue))
  {
    // If the type definition is of type "object"
    // and has a "properties" definition we need
    // to handle these as well
    if (value.isMember("properties") && value["properties"].isObject())
    {
      // Get all child elements of the "properties"
      // object and loop through them
      for (CVariant::const_iterator_map itr = value["properties"].begin_map(); itr != value["properties"].end_map(); ++itr)
      {
        // Create a new type definition, store the name
        // of the current property into it, parse it
        // recursively and add its default value
        // to the current type's default value
        JSONSchemaTypeDefinitionPtr propertyType = JSONSchemaTypeDefinitionPtr(new JSONSchemaTypeDefinition());
        propertyType->name = itr->first;
        if (!propertyType->Parse(itr->second))
        {
          missingReference = propertyType->missingReference;
          return false;
        }
        defaultValue[itr->first] = propertyType->defaultValue;
        properties.add(propertyType);
      }
    }

    hasAdditionalProperties = true;
    additionalProperties = JSONSchemaTypeDefinitionPtr(new JSONSchemaTypeDefinition());
    if (value.isMember("additionalProperties"))
    {
      if (value["additionalProperties"].isBoolean())
      {
        hasAdditionalProperties = value["additionalProperties"].asBoolean();
        if (!hasAdditionalProperties)
        {
          additionalProperties.reset();
        }
      }
      else if (value["additionalProperties"].isObject() && !value["additionalProperties"].isNull())
      {
        if (!additionalProperties->Parse(value["additionalProperties"]))
        {
          missingReference = additionalProperties->missingReference;
          hasAdditionalProperties = false;
          additionalProperties.reset();

          CLog::Log(LOGDEBUG, "JSONRPC: Invalid additionalProperties schema definition in type {}",
                    name);
          return false;
        }
      }
      else
      {
        CLog::Log(LOGDEBUG, "JSONRPC: Invalid additionalProperties definition in type {}", name);
        return false;
      }
    }
  }

  // If the defined parameter is an array
  // we need to check for detailed definitions
  // of the array items
  if (HasType(type, ArrayValue))
  {
    // Check for "uniqueItems" field
    if (value.isMember("uniqueItems") && value["uniqueItems"].isBoolean())
      uniqueItems = value["uniqueItems"].asBoolean();
    else
      uniqueItems = false;

    // Check for "additionalItems" field
    if (value.isMember("additionalItems"))
    {
      // If it is an object, there is only one schema for it
      if (value["additionalItems"].isObject())
      {
        JSONSchemaTypeDefinitionPtr additionalItem = JSONSchemaTypeDefinitionPtr(new JSONSchemaTypeDefinition());
        if (additionalItem->Parse(value["additionalItems"]))
          additionalItems.push_back(additionalItem);
        else
        {
          CLog::Log(LOGDEBUG, "Invalid \"additionalItems\" value for type {}", name);
          missingReference = additionalItem->missingReference;
          return false;
        }
      }
      // If it is an array there may be multiple schema definitions
      else if (value["additionalItems"].isArray())
      {
        for (unsigned int itemIndex = 0; itemIndex < value["additionalItems"].size(); itemIndex++)
        {
          JSONSchemaTypeDefinitionPtr additionalItem = JSONSchemaTypeDefinitionPtr(new JSONSchemaTypeDefinition());

          if (additionalItem->Parse(value["additionalItems"][itemIndex]))
            additionalItems.push_back(additionalItem);
          else
          {
            CLog::Log(LOGDEBUG, "Invalid \"additionalItems\" value (item {}) for type {}",
                      itemIndex, name);
            missingReference = additionalItem->missingReference;
            return false;
          }
        }
      }
      // If it is not a (array of) schema and not a bool (default value is false)
      // it has an invalid value
      else if (!value["additionalItems"].isBoolean())
      {
        CLog::Log(LOGDEBUG, "Invalid \"additionalItems\" definition for type {}", name);
        return false;
      }
    }

    // If the "items" field is a single object
    // we can parse that directly
    if (value.isMember("items"))
    {
      if (value["items"].isObject())
      {
        JSONSchemaTypeDefinitionPtr item = JSONSchemaTypeDefinitionPtr(new JSONSchemaTypeDefinition());
        if (!item->Parse(value["items"]))
        {
          CLog::Log(LOGDEBUG, "Invalid item definition in \"items\" for type {}", name);
          missingReference = item->missingReference;
          return false;
        }
        items.push_back(item);
      }
      // Otherwise if it is an array we need to
      // parse all elements and store them
      else if (value["items"].isArray())
      {
        for (CVariant::const_iterator_array itemItr = value["items"].begin_array(); itemItr != value["items"].end_array(); ++itemItr)
        {
          JSONSchemaTypeDefinitionPtr item = JSONSchemaTypeDefinitionPtr(new JSONSchemaTypeDefinition());
          if (!item->Parse(*itemItr))
          {
            CLog::Log(LOGDEBUG, "Invalid item definition in \"items\" array for type {}", name);
            missingReference = item->missingReference;
            return false;
          }
          items.push_back(item);
        }
      }
    }

    minItems = (unsigned int)value["minItems"].asUnsignedInteger(0);
    maxItems = (unsigned int)value["maxItems"].asUnsignedInteger(0);
  }

  if (HasType(type, NumberValue) || HasType(type, IntegerValue))
  {
    if ((type & NumberValue) == NumberValue)
    {
      minimum = value["minimum"].asDouble(-std::numeric_limits<double>::max());
      maximum = value["maximum"].asDouble(std::numeric_limits<double>::max());
    }
    else if ((type  & IntegerValue) == IntegerValue)
    {
      minimum = (double)value["minimum"].asInteger(std::numeric_limits<int>::min());
      maximum = (double)value["maximum"].asInteger(std::numeric_limits<int>::max());
    }

    exclusiveMinimum = value["exclusiveMinimum"].asBoolean(false);
    exclusiveMaximum = value["exclusiveMaximum"].asBoolean(false);
    divisibleBy = (unsigned int)value["divisibleBy"].asUnsignedInteger(0);
  }

  if (HasType(type, StringValue))
  {
    minLength = (int)value["minLength"].asInteger(-1);
    maxLength = (int)value["maxLength"].asInteger(-1);
  }

  // If the type definition is neither an
  // "object" nor an "array" we can check
  // for an "enum" definition
  if (value.isMember("enum") && value["enum"].isArray())
  {
    // Loop through all elements in the "enum" array
    for (CVariant::const_iterator_array enumItr = value["enum"].begin_array(); enumItr != value["enum"].end_array(); ++enumItr)
    {
      // Check for duplicates and eliminate them
      bool approved = true;
      for (unsigned int approvedIndex = 0; approvedIndex < enums.size(); approvedIndex++)
      {
        if (*enumItr == enums.at(approvedIndex))
        {
          approved = false;
          break;
        }
      }

      // Only add the current item to the enum value
      // list if it is not duplicate
      if (approved)
        enums.push_back(*enumItr);
    }
  }

  if (type != ObjectValue)
  {
    // If there is a definition for a default value and its type
    // matches the type of the parameter we can parse it
    bool ok = false;
    if (value.isMember("default") && IsType(value["default"], type))
    {
      if (enums.size() <= 0)
        ok = true;
      // If the type has an enum definition we must make
      // sure that the default value is a valid enum value
      else
      {
        for (std::vector<CVariant>::const_iterator itr = enums.begin(); itr != enums.end(); ++itr)
        {
          if (value["default"] == *itr)
          {
            ok = true;
            break;
          }
        }
      }
    }

    if (ok)
      defaultValue = value["default"];
    else
    {
      // If the type of the default value definition does not
      // match the type of the parameter we have to log this
      if (value.isMember("default") && !IsType(value["default"], type))
        CLog::Log(LOGDEBUG, "JSONRPC: Parameter {} has an invalid default value", name);

      // If the type contains an "enum" we need to get the
      // default value from the first enum value
      if (enums.size() > 0)
        defaultValue = enums.at(0);
      // otherwise set a default value instead
      else
        SetDefaultValue(defaultValue, type);
    }
  }

  return true;
}

JSONRPC_STATUS JSONSchemaTypeDefinition::Check(const CVariant& value,
                                               CVariant& outputValue,
                                               CVariant& errorData) const
{
  if (!name.empty())
    errorData["name"] = name;
  SchemaValueTypeToJson(type, errorData["type"]);
  std::string errorMessage;

  // Let's check the type of the provided parameter
  if (!IsType(value, type))
  {
    errorMessage = StringUtils::Format("Invalid type {} received", ValueTypeToString(value.type()));
    errorData["message"] = errorMessage.c_str();
    return InvalidParams;
  }
  else if (value.isNull() && !HasType(type, NullValue))
  {
    errorData["message"] = "Received value is null";
    return InvalidParams;
  }

  // Let's check if we have to handle a union type
  if (unionTypes.size() > 0)
  {
    bool ok = false;
    for (unsigned int unionIndex = 0; unionIndex < unionTypes.size(); unionIndex++)
    {
      CVariant dummyError;
      CVariant testOutput = outputValue;
      if (unionTypes.at(unionIndex)->Check(value, testOutput, dummyError) == OK)
      {
        ok = true;
        outputValue = testOutput;
        break;
      }
    }

    if (!ok)
    {
      errorData["message"] = "Received value does not match any of the union type definitions";
      return InvalidParams;
    }
  }

  // First we need to check if this type extends another
  // type and if so we need to check against the extended
  // type first
  if (extends.size() > 0)
  {
    for (unsigned int extendsIndex = 0; extendsIndex < extends.size(); extendsIndex++)
    {
      JSONRPC_STATUS status = extends.at(extendsIndex)->Check(value, outputValue, errorData);

      if (status != OK)
      {
        CLog::Log(LOGDEBUG, "JSONRPC: Value does not match extended type {} of type {}",
                  extends.at(extendsIndex)->ID, name);
        errorMessage = StringUtils::Format("value does not match extended type {}",
                                           extends.at(extendsIndex)->ID);
        errorData["message"] = errorMessage.c_str();
        return status;
      }
    }
  }

  // If it is an array we need to
  // - check the type of every element ("items")
  // - check if they need to be unique ("uniqueItems")
  if (HasType(type, ArrayValue) && value.isArray())
  {
    outputValue = CVariant(CVariant::VariantTypeArray);
    // Check the number of items against minItems and maxItems
    if ((minItems > 0 && value.size() < minItems) || (maxItems > 0 && value.size() > maxItems))
    {
      CLog::Log(
          LOGDEBUG,
          "JSONRPC: Number of array elements does not match minItems and/or maxItems in type {}",
          name);
      if (minItems > 0 && maxItems > 0)
        errorMessage = StringUtils::Format("Between {} and {} array items expected but {} received",
                                           minItems, maxItems, value.size());
      else if (minItems > 0)
        errorMessage = StringUtils::Format("At least {} array items expected but only {} received",
                                           minItems, value.size());
      else
        errorMessage = StringUtils::Format("Only {} array items expected but {} received", maxItems,
                                           value.size());
      errorData["message"] = errorMessage.c_str();
      return InvalidParams;
    }

    if (items.size() == 0)
      outputValue = value;
    else if (items.size() == 1)
    {
      JSONSchemaTypeDefinitionPtr itemType = items.at(0);

      // Loop through all array elements
      for (unsigned int arrayIndex = 0; arrayIndex < value.size(); arrayIndex++)
      {
        CVariant temp;
        JSONRPC_STATUS status = itemType->Check(value[arrayIndex], temp, errorData["property"]);
        outputValue.push_back(temp);
        if (status != OK)
        {
          CLog::Log(LOGDEBUG, "JSONRPC: Array element at index {} does not match in type {}",
                    arrayIndex, name);
          errorMessage =
              StringUtils::Format("array element at index {} does not match", arrayIndex);
          errorData["message"] = errorMessage.c_str();
          return status;
        }
      }
    }
    // We have more than one element in "items"
    // so we have tuple typing, which means that
    // every element in the value array must match
    // with the type at the same position in the
    // "items" array
    else
    {
      // If the number of elements in the value array
      // does not match the number of elements in the
      // "items" array and additional items are not
      // allowed there is no need to check every element
      if (value.size() < items.size() || (value.size() != items.size() && additionalItems.size() == 0))
      {
        CLog::Log(LOGDEBUG, "JSONRPC: One of the array elements does not match in type {}", name);
        errorMessage = StringUtils::Format("{0} array elements expected but {1} received", items.size(), value.size());
        errorData["message"] = errorMessage.c_str();
        return InvalidParams;
      }

      // Loop through all array elements until there
      // are either no more schemas in the "items"
      // array or no more elements in the value's array
      unsigned int arrayIndex;
      for (arrayIndex = 0; arrayIndex < std::min(items.size(), (size_t)value.size()); arrayIndex++)
      {
        JSONRPC_STATUS status = items.at(arrayIndex)->Check(value[arrayIndex], outputValue[arrayIndex], errorData["property"]);
        if (status != OK)
        {
          CLog::Log(
              LOGDEBUG,
              "JSONRPC: Array element at index {} does not match with items schema in type {}",
              arrayIndex, name);
          return status;
        }
      }

      if (additionalItems.size() > 0)
      {
        // Loop through the rest of the elements
        // in the array and check them against the
        // "additionalItems"
        for (; arrayIndex < value.size(); arrayIndex++)
        {
          bool ok = false;
          for (unsigned int additionalIndex = 0; additionalIndex < additionalItems.size(); additionalIndex++)
          {
            CVariant dummyError;
            if (additionalItems.at(additionalIndex)->Check(value[arrayIndex], outputValue[arrayIndex], dummyError) == OK)
            {
              ok = true;
              break;
            }
          }

          if (!ok)
          {
            CLog::Log(LOGDEBUG,
                      "JSONRPC: Array contains non-conforming additional items in type {}", name);
            errorMessage = StringUtils::Format(
                "Array element at index {} does not match the \"additionalItems\" schema",
                arrayIndex);
            errorData["message"] = errorMessage.c_str();
            return InvalidParams;
          }
        }
      }
    }

    // If every array element is unique we need to check each one
    if (uniqueItems)
    {
      for (unsigned int checkingIndex = 0; checkingIndex < outputValue.size(); checkingIndex++)
      {
        for (unsigned int checkedIndex = checkingIndex + 1; checkedIndex < outputValue.size(); checkedIndex++)
        {
          // If two elements are the same they are not unique
          if (outputValue[checkingIndex] == outputValue[checkedIndex])
          {
            CLog::Log(LOGDEBUG, "JSONRPC: Not unique array element at index {} and {} in type {}",
                      checkingIndex, checkedIndex, name);
            errorMessage = StringUtils::Format(
                "Array element at index {} is not unique (same as array element at index {})",
                checkingIndex, checkedIndex);
            errorData["message"] = errorMessage.c_str();
            return InvalidParams;
          }
        }
      }
    }

    return OK;
  }

  // If it is an object we need to check every element
  // against the defined "properties"
  if (HasType(type, ObjectValue) && value.isObject())
  {
    unsigned int handled = 0;
    JSONSchemaTypeDefinition::CJsonSchemaPropertiesMap::JSONSchemaPropertiesIterator propertiesEnd = properties.end();
    JSONSchemaTypeDefinition::CJsonSchemaPropertiesMap::JSONSchemaPropertiesIterator propertiesIterator;
    for (propertiesIterator = properties.begin(); propertiesIterator != propertiesEnd; ++propertiesIterator)
    {
      if (value.isMember(propertiesIterator->second->name))
      {
        JSONRPC_STATUS status = propertiesIterator->second->Check(value[propertiesIterator->second->name], outputValue[propertiesIterator->second->name], errorData["property"]);
        if (status != OK)
        {
          CLog::Log(LOGDEBUG, "JSONRPC: Invalid property \"{}\" in type {}",
                    propertiesIterator->second->name, name);
          return status;
        }
        handled++;
      }
      else if (propertiesIterator->second->optional)
        outputValue[propertiesIterator->second->name] = propertiesIterator->second->defaultValue;
      else
      {
        errorData["property"]["name"] = propertiesIterator->second->name.c_str();
        errorData["property"]["type"] = SchemaValueTypeToString(propertiesIterator->second->type);
        errorData["message"] = "Missing property";
        return InvalidParams;
      }
    }

    // Additional properties are not allowed
    if (handled < value.size())
    {
      // If additional properties are allowed we need to check if
      // they match the defined schema
      if (hasAdditionalProperties && additionalProperties != NULL)
      {
        CVariant::const_iterator_map iter;
        CVariant::const_iterator_map iterEnd = value.end_map();
        for (iter = value.begin_map(); iter != iterEnd; ++iter)
        {
          if (properties.find(iter->first) != properties.end())
            continue;

          // If the additional property is of type "any"
          // we can simply copy its value to the output
          // object
          if (additionalProperties->type == AnyValue)
          {
            outputValue[iter->first] = value[iter->first];
            continue;
          }

          JSONRPC_STATUS status = additionalProperties->Check(value[iter->first], outputValue[iter->first], errorData["property"]);
          if (status != OK)
          {
            CLog::Log(LOGDEBUG, "JSONRPC: Invalid additional property \"{}\" in type {}",
                      iter->first, name);
            return status;
          }
        }
      }
      // If we still have unchecked properties but additional
      // properties are not allowed, we have invalid parameters
      else if (!hasAdditionalProperties || additionalProperties == NULL)
      {
        errorData["message"] = "Unexpected additional properties received";
        errorData.erase("property");
        return InvalidParams;
      }
    }

    return OK;
  }

  // It's neither an array nor an object

  // If it can only take certain values ("enum")
  // we need to check against those
  if (enums.size() > 0)
  {
    bool valid = false;
    for (const auto& enumItr : enums)
    {
      if (enumItr == value)
      {
        valid = true;
        break;
      }
    }

    if (!valid)
    {
      CLog::Log(LOGDEBUG, "JSONRPC: Value does not match any of the enum values in type {}", name);
      errorData["message"] = "Received value does not match any of the defined enum values";
      return InvalidParams;
    }
  }

  // If we have a number or an integer type, we need
  // to check the minimum and maximum values
  if ((HasType(type, NumberValue) && value.isDouble()) || (HasType(type, IntegerValue) && value.isInteger()))
  {
    double numberValue;
    if (value.isDouble())
      numberValue = value.asDouble();
    else
      numberValue = (double)value.asInteger();
    // Check minimum
    if ((exclusiveMinimum && numberValue <= minimum) || (!exclusiveMinimum && numberValue < minimum) ||
    // Check maximum
        (exclusiveMaximum && numberValue >= maximum) || (!exclusiveMaximum && numberValue > maximum))
    {
      CLog::Log(LOGDEBUG, "JSONRPC: Value does not lay between minimum and maximum in type {}",
                name);
      if (value.isDouble())
        errorMessage =
            StringUtils::Format("Value between {:f} ({}) and {:f} ({}) expected but {:f} received",
                                minimum, exclusiveMinimum ? "exclusive" : "inclusive", maximum,
                                exclusiveMaximum ? "exclusive" : "inclusive", numberValue);
      else
        errorMessage = StringUtils::Format(
            "Value between {} ({}) and {} ({}) expected but {} received", (int)minimum,
            exclusiveMinimum ? "exclusive" : "inclusive", (int)maximum,
            exclusiveMaximum ? "exclusive" : "inclusive", (int)numberValue);
      errorData["message"] = errorMessage.c_str();
      return InvalidParams;
    }
    // Check divisibleBy
    if ((HasType(type, IntegerValue) && divisibleBy > 0 && ((int)numberValue % divisibleBy) != 0))
    {
      CLog::Log(LOGDEBUG, "JSONRPC: Value does not meet divisibleBy requirements in type {}", name);
      errorMessage = StringUtils::Format("Value should be divisible by {} but {} received",
                                         divisibleBy, (int)numberValue);
      errorData["message"] = errorMessage.c_str();
      return InvalidParams;
    }
  }

  // If we have a string, we need to check the length
  if (HasType(type, StringValue) && value.isString())
  {
    int size = static_cast<int>(value.asString().size());
    if (size < minLength)
    {
      CLog::Log(LOGDEBUG, "JSONRPC: Value does not meet minLength requirements in type {}", name);
      errorMessage = StringUtils::Format(
          "Value should have a minimum length of {} but has a length of {}", minLength, size);
      errorData["message"] = errorMessage.c_str();
      return InvalidParams;
    }

    if (maxLength >= 0 && size > maxLength)
    {
      CLog::Log(LOGDEBUG, "JSONRPC: Value does not meet maxLength requirements in type {}", name);
      errorMessage = StringUtils::Format(
          "Value should have a maximum length of {} but has a length of {}", maxLength, size);
      errorData["message"] = errorMessage.c_str();
      return InvalidParams;
    }
  }

  // Otherwise it can have any value
  outputValue = value;
  return OK;
}

void JSONSchemaTypeDefinition::Print(bool isParameter, bool isGlobal, bool printDefault, bool printDescriptions, CVariant &output) const
{
  bool typeReference = false;

  // Printing general fields
  if (isParameter)
    output["name"] = name;

  if (isGlobal)
    output["id"] = ID;
  else if (!ID.empty())
  {
    output["$ref"] = ID;
    typeReference = true;
  }

  if (printDescriptions && !description.empty())
    output["description"] = description;

  if (isParameter || printDefault)
  {
    if (!optional)
      output["required"] = true;
    if (optional && type != ObjectValue && type != ArrayValue)
      output["default"] = defaultValue;
  }

  if (!typeReference)
  {
    if (extends.size() == 1)
    {
      output["extends"] = extends.at(0)->ID;
    }
    else if (extends.size() > 1)
    {
      output["extends"] = CVariant(CVariant::VariantTypeArray);
      for (unsigned int extendsIndex = 0; extendsIndex < extends.size(); extendsIndex++)
        output["extends"].append(extends.at(extendsIndex)->ID);
    }
    else if (unionTypes.size() > 0)
    {
      output["type"] = CVariant(CVariant::VariantTypeArray);
      for (unsigned int unionIndex = 0; unionIndex < unionTypes.size(); unionIndex++)
      {
        CVariant unionOutput = CVariant(CVariant::VariantTypeObject);
        unionTypes.at(unionIndex)->Print(false, false, false, printDescriptions, unionOutput);
        output["type"].append(unionOutput);
      }
    }
    else
      CJSONUtils::SchemaValueTypeToJson(type, output["type"]);

    // Printing enum field
    if (enums.size() > 0)
    {
      output["enums"] = CVariant(CVariant::VariantTypeArray);
      for (unsigned int enumIndex = 0; enumIndex < enums.size(); enumIndex++)
        output["enums"].append(enums.at(enumIndex));
    }

    // Printing integer/number fields
    if (CJSONUtils::HasType(type, IntegerValue) || CJSONUtils::HasType(type, NumberValue))
    {
      if (CJSONUtils::HasType(type, NumberValue))
      {
        if (minimum > -std::numeric_limits<double>::max())
          output["minimum"] = minimum;
        if (maximum < std::numeric_limits<double>::max())
          output["maximum"] = maximum;
      }
      else
      {
        if (minimum > std::numeric_limits<int>::min())
          output["minimum"] = (int)minimum;
        if (maximum < std::numeric_limits<int>::max())
          output["maximum"] = (int)maximum;
      }

      if (exclusiveMinimum)
        output["exclusiveMinimum"] = true;
      if (exclusiveMaximum)
        output["exclusiveMaximum"] = true;
      if (divisibleBy > 0)
        output["divisibleBy"] = divisibleBy;
    }
    if (CJSONUtils::HasType(type, StringValue))
    {
      if (minLength >= 0)
        output["minLength"] = minLength;
      if (maxLength >= 0)
        output["maxLength"] = maxLength;
    }

    // Print array fields
    if (CJSONUtils::HasType(type, ArrayValue))
    {
      if (items.size() == 1)
      {
        items.at(0)->Print(false, false, false, printDescriptions, output["items"]);
      }
      else if (items.size() > 1)
      {
        output["items"] = CVariant(CVariant::VariantTypeArray);
        for (unsigned int itemIndex = 0; itemIndex < items.size(); itemIndex++)
        {
          CVariant item = CVariant(CVariant::VariantTypeObject);
          items.at(itemIndex)->Print(false, false, false, printDescriptions, item);
          output["items"].append(item);
        }
      }

      if (minItems > 0)
        output["minItems"] = minItems;
      if (maxItems > 0)
        output["maxItems"] = maxItems;

      if (additionalItems.size() == 1)
      {
        additionalItems.at(0)->Print(false, false, false, printDescriptions, output["additionalItems"]);
      }
      else if (additionalItems.size() > 1)
      {
        output["additionalItems"] = CVariant(CVariant::VariantTypeArray);
        for (unsigned int addItemIndex = 0; addItemIndex < additionalItems.size(); addItemIndex++)
        {
          CVariant item = CVariant(CVariant::VariantTypeObject);
          additionalItems.at(addItemIndex)->Print(false, false, false, printDescriptions, item);
          output["additionalItems"].append(item);
        }
      }

      if (uniqueItems)
        output["uniqueItems"] = true;
    }

    // Print object fields
    if (CJSONUtils::HasType(type, ObjectValue))
    {
      if (properties.size() > 0)
      {
        output["properties"] = CVariant(CVariant::VariantTypeObject);

        JSONSchemaTypeDefinition::CJsonSchemaPropertiesMap::JSONSchemaPropertiesIterator propertiesEnd = properties.end();
        JSONSchemaTypeDefinition::CJsonSchemaPropertiesMap::JSONSchemaPropertiesIterator propertiesIterator;
        for (propertiesIterator = properties.begin(); propertiesIterator != propertiesEnd; ++propertiesIterator)
        {
          propertiesIterator->second->Print(false, false, true, printDescriptions, output["properties"][propertiesIterator->first]);
        }
      }

      if (!hasAdditionalProperties)
        output["additionalProperties"] = false;
      else if (additionalProperties != NULL && additionalProperties->type != AnyValue)
        additionalProperties->Print(false, false, true, printDescriptions, output["additionalProperties"]);
    }
  }
}

void JSONSchemaTypeDefinition::ResolveReference()
{
  // Check and set the reference type before recursing
  // to guard against cycles
  if (referencedTypeSet)
    return;

  referencedTypeSet = true;

  // Take care of all nested types
  for (const auto& it : extends)
    it->ResolveReference();
  for (const auto& it : unionTypes)
    it->ResolveReference();
  for (const auto& it : items)
    it->ResolveReference();
  for (const auto& it : additionalItems)
    it->ResolveReference();
  for (const auto& it : properties)
    it.second->ResolveReference();

  if (additionalProperties)
    additionalProperties->ResolveReference();

  if (referencedType == nullptr)
    return;

  std::string origName = name;
  std::string origDescription = description;
  bool origOptional = optional;
  CVariant origDefaultValue = defaultValue;
  JSONSchemaTypeDefinitionPtr referencedTypeDef = referencedType;

  // set all the values from the given type definition
  *this = *referencedType;

  // restore the original values
  if (!origName.empty())
    name = origName;

  if (!origDescription.empty())
    description = origDescription;

  if (!origOptional)
    optional = origOptional;

  if (!origDefaultValue.isNull())
    defaultValue = origDefaultValue;

  if (referencedTypeDef.get() != NULL)
    referencedType = referencedTypeDef;

  // This will have been overwritten by the copy of the reference
  // type so we need to set it again
  referencedTypeSet = true;
}

JSONSchemaTypeDefinition::CJsonSchemaPropertiesMap::CJsonSchemaPropertiesMap() :
   m_propertiesmap(std::map<std::string, JSONSchemaTypeDefinitionPtr>())
{
}

void JSONSchemaTypeDefinition::CJsonSchemaPropertiesMap::add(
    const JSONSchemaTypeDefinitionPtr& property)
{
  std::string name = property->name;
  StringUtils::ToLower(name);
  m_propertiesmap[name] = property;
}

JSONSchemaTypeDefinition::CJsonSchemaPropertiesMap::JSONSchemaPropertiesIterator JSONSchemaTypeDefinition::CJsonSchemaPropertiesMap::begin() const
{
  return m_propertiesmap.begin();
}

JSONSchemaTypeDefinition::CJsonSchemaPropertiesMap::JSONSchemaPropertiesIterator JSONSchemaTypeDefinition::CJsonSchemaPropertiesMap::find(const std::string& key) const
{
  return m_propertiesmap.find(key);
}

JSONSchemaTypeDefinition::CJsonSchemaPropertiesMap::JSONSchemaPropertiesIterator JSONSchemaTypeDefinition::CJsonSchemaPropertiesMap::end() const
{
  return m_propertiesmap.end();
}

unsigned int JSONSchemaTypeDefinition::CJsonSchemaPropertiesMap::size() const
{
  return static_cast<unsigned int>(m_propertiesmap.size());
}

JsonRpcMethod::JsonRpcMethod()
  : missingReference(),
    name(),
    method(NULL),
    description(),
    parameters(),
    returns(new JSONSchemaTypeDefinition())
{ }

bool JsonRpcMethod::Parse(const CVariant &value)
{
  // Parse XBMC specific information about the method
  if (value.isMember("transport") && value["transport"].isArray())
  {
    int transport = 0;
    for (unsigned int index = 0; index < value["transport"].size(); index++)
      transport |= StringToTransportLayer(value["transport"][index].asString());

    transportneed = (TransportLayerCapability)transport;
  }
  else
    transportneed = StringToTransportLayer(value.isMember("transport") ? value["transport"].asString() : "");

  if (value.isMember("permission") && value["permission"].isArray())
  {
    int permissions = 0;
    for (unsigned int index = 0; index < value["permission"].size(); index++)
      permissions |= StringToPermission(value["permission"][index].asString());

    permission = (OperationPermission)permissions;
  }
  else
    permission = StringToPermission(value.isMember("permission") ? value["permission"].asString() : "");

  description = GetString(value["description"], "");

  // Check whether there are parameters defined
  if (value.isMember("params") && value["params"].isArray())
  {
    // Loop through all defined parameters
    for (unsigned int paramIndex = 0; paramIndex < value["params"].size(); paramIndex++)
    {
      CVariant parameter = value["params"][paramIndex];
      // If the parameter definition does not contain a valid "name" or
      // "type" element we will ignore it
      if (!parameter.isMember("name") || !parameter["name"].isString() ||
         (!parameter.isMember("type") && !parameter.isMember("$ref") && !parameter.isMember("extends")) ||
         (parameter.isMember("type") && !parameter["type"].isString() && !parameter["type"].isArray()) ||
         (parameter.isMember("$ref") && !parameter["$ref"].isString()) ||
         (parameter.isMember("extends") && !parameter["extends"].isString() && !parameter["extends"].isArray()))
      {
        CLog::Log(LOGDEBUG, "JSONRPC: Method {} has a badly defined parameter", name);
        return false;
      }

      // Parse the parameter and add it to the list
      // of defined parameters
      JSONSchemaTypeDefinitionPtr param = JSONSchemaTypeDefinitionPtr(new JSONSchemaTypeDefinition());
      if (!parseParameter(parameter, param))
      {
        missingReference = param->missingReference;
        return false;
      }
      parameters.push_back(param);
    }
  }

  // Parse the return value of the method
  if (!parseReturn(value))
  {
    missingReference = returns->missingReference;
    return false;
  }

  return true;
}

JSONRPC_STATUS JsonRpcMethod::Check(const CVariant &requestParameters, ITransportLayer *transport, IClient *client, bool notification, MethodCall &methodCall, CVariant &outputParameters) const
{
  if (transport != NULL && (transport->GetCapabilities() & transportneed) == transportneed)
  {
    if (client != NULL && (client->GetPermissionFlags() & permission) == permission && (!notification || (permission & OPERATION_PERMISSION_NOTIFICATION) == permission))
    {
      methodCall = method;

      // Count the number of actually handled (present)
      // parameters
      unsigned int handled = 0;
      CVariant errorData = CVariant(CVariant::VariantTypeObject);
      errorData["method"] = name;

      // Loop through all the parameters to check
      for (unsigned int i = 0; i < parameters.size(); i++)
      {
        // Evaluate the current parameter
        JSONRPC_STATUS status = checkParameter(requestParameters, parameters.at(i), i, outputParameters, handled, errorData);
        if (status != OK)
        {
          // Return the error data object in the outputParameters reference
          outputParameters = errorData;
          return status;
        }
      }

      // Check if there were unnecessary parameters
      if (handled < requestParameters.size())
      {
        errorData["message"] = "Too many parameters";
        outputParameters = errorData;
        return InvalidParams;
      }

      return OK;
    }
    else
      return BadPermission;
  }

  return MethodNotFound;
}

bool JsonRpcMethod::parseParameter(const CVariant& value,
                                   const JSONSchemaTypeDefinitionPtr& parameter)
{
  parameter->name = GetString(value["name"], "");

  // Parse the type and default value of the parameter
  return parameter->Parse(value, true);
}

bool JsonRpcMethod::parseReturn(const CVariant &value)
{
  // Only parse the "returns" definition if there is one
  if (!value.isMember("returns"))
  {
    returns->type = NullValue;
    return true;
  }

  // If the type of the return value is defined as a simple string we can parse it directly
  if (value["returns"].isString())
    return CJSONServiceDescription::parseJSONSchemaType(value["returns"], returns->unionTypes, returns->type, missingReference);

  // otherwise we have to parse the whole type definition
  if (!returns->Parse(value["returns"]))
  {
    missingReference = returns->missingReference;
    return false;
  }

  return true;
}

JSONRPC_STATUS JsonRpcMethod::checkParameter(const CVariant& requestParameters,
                                             const JSONSchemaTypeDefinitionPtr& type,
                                             unsigned int position,
                                             CVariant& outputParameters,
                                             unsigned int& handled,
                                             CVariant& errorData)
{
  // Let's check if the parameter has been provided
  if (ParameterExists(requestParameters, type->name, position))
  {
    // Get the parameter
    CVariant parameterValue = GetParameter(requestParameters, type->name, position);

    // Evaluate the type of the parameter
    JSONRPC_STATUS status = type->Check(parameterValue, outputParameters[type->name], errorData["stack"]);
    if (status != OK)
      return status;

    // The parameter was present and valid
    handled++;
  }
  // If the parameter has not been provided but is optional
  // we can use its default value
  else if (type->optional)
    outputParameters[type->name] = type->defaultValue;
  // The parameter is required but has not been provided => invalid
  else
  {
    errorData["stack"]["name"] = type->name;
    SchemaValueTypeToJson(type->type, errorData["stack"]["type"]);
    errorData["stack"]["message"] = "Missing parameter";
    return InvalidParams;
  }

  return OK;
}

void CJSONServiceDescription::ResolveReferences()
{
  for (const auto& it : m_types)
    it.second->ResolveReference();
}

void CJSONServiceDescription::Cleanup()
{
  // reset all of the static data
  m_notifications.clear();
  m_actionMap.clear();
  m_types.clear();
  m_incompleteDefinitions.clear();
}

bool CJSONServiceDescription::prepareDescription(std::string &description, CVariant &descriptionObject, std::string &name)
{
  if (description.empty())
  {
    CLog::Log(LOGERROR, "JSONRPC: Missing JSON Schema definition for \"{}\"", name);
    return false;
  }

  if (description.at(0) != '{')
    description = StringUtils::Format("{{{:s}}}", description);

  // Make sure the method description actually exists and represents an object
  if (!CJSONVariantParser::Parse(description, descriptionObject) || !descriptionObject.isObject())
  {
    CLog::Log(LOGERROR, "JSONRPC: Unable to parse JSON Schema definition for \"{}\"", name);
    return false;
  }

  CVariant::const_iterator_map member = descriptionObject.begin_map();
  if (member != descriptionObject.end_map())
    name = member->first;

  if (name.empty() ||
     (!descriptionObject[name].isMember("type") && !descriptionObject[name].isMember("$ref") && !descriptionObject[name].isMember("extends")))
  {
    CLog::Log(LOGERROR, "JSONRPC: Invalid JSON Schema definition for \"{}\"", name);
    return false;
  }

  return true;
}

bool CJSONServiceDescription::addMethod(const std::string &jsonMethod, MethodCall method)
{
  CVariant descriptionObject;
  std::string methodName;

  std::string modJsonMethod = jsonMethod;
  // Make sure the method description actually exists and represents an object
  if (!prepareDescription(modJsonMethod, descriptionObject, methodName))
  {
    CLog::Log(LOGERROR, "JSONRPC: Invalid JSON Schema definition for method \"{}\"", methodName);
    return false;
  }

  if (m_actionMap.find(methodName) != m_actionMap.end())
  {
    CLog::Log(LOGERROR, "JSONRPC: There already is a method with the name \"{}\"", methodName);
    return false;
  }

  std::string type = GetString(descriptionObject[methodName]["type"], "");
  if (type.compare("method") != 0)
  {
    CLog::Log(LOGERROR, "JSONRPC: Invalid JSON type for method \"{}\"", methodName);
    return false;
  }

  if (method == NULL)
  {
    unsigned int size = sizeof(m_methodMaps) / sizeof(JsonRpcMethodMap);
    for (unsigned int index = 0; index < size; index++)
    {
      if (methodName.compare(m_methodMaps[index].name) == 0)
      {
        method = m_methodMaps[index].method;
        break;
      }
    }

    if (method == NULL)
    {
      CLog::Log(LOGERROR, "JSONRPC: Missing implementation for method \"{}\"", methodName);
      return false;
    }
  }

  // Parse the details of the method
  JsonRpcMethod newMethod;
  newMethod.name = methodName;
  newMethod.method = method;

  if (!newMethod.Parse(descriptionObject[newMethod.name]))
  {
    CLog::Log(LOGERROR, "JSONRPC: Could not parse method \"{}\"", methodName);
    if (!newMethod.missingReference.empty())
    {
      IncompleteSchemaDefinition incomplete;
      incomplete.Schema = modJsonMethod;
      incomplete.Type = SchemaDefinitionMethod;
      incomplete.Method = method;

      IncompleteSchemaDefinitionMap::iterator iter = m_incompleteDefinitions.find(newMethod.missingReference);
      if (iter == m_incompleteDefinitions.end())
        m_incompleteDefinitions[newMethod.missingReference] = std::vector<IncompleteSchemaDefinition>();

      CLog::Log(
          LOGINFO,
          "JSONRPC: Adding method \"{}\" to list of incomplete definitions (waiting for \"{}\")",
          methodName, newMethod.missingReference);
      m_incompleteDefinitions[newMethod.missingReference].push_back(incomplete);
    }

    return false;
  }

  m_actionMap.add(newMethod);

  return true;
}

bool CJSONServiceDescription::AddType(const std::string &jsonType)
{
  CVariant descriptionObject;
  std::string typeName;

  std::string modJsonType = jsonType;
  if (!prepareDescription(modJsonType, descriptionObject, typeName))
  {
    CLog::Log(LOGERROR, "JSONRPC: Invalid JSON Schema definition for type \"{}\"", typeName);
    return false;
  }

  if (m_types.find(typeName) != m_types.end())
  {
    CLog::Log(LOGERROR, "JSONRPC: There already is a type with the name \"{}\"", typeName);
    return false;
  }

  // Make sure the "id" attribute is correctly populated
  descriptionObject[typeName]["id"] = typeName;

  JSONSchemaTypeDefinitionPtr globalType = JSONSchemaTypeDefinitionPtr(new JSONSchemaTypeDefinition());
  globalType->name = typeName;
  globalType->ID = typeName;
  CJSONServiceDescription::addReferenceTypeDefinition(globalType);

  if (!globalType->Parse(descriptionObject[typeName]))
  {
    CLog::Log(LOGWARNING, "JSONRPC: Could not parse type \"{}\"", typeName);
    CJSONServiceDescription::removeReferenceTypeDefinition(typeName);
    if (!globalType->missingReference.empty())
    {
      IncompleteSchemaDefinition incomplete;
      incomplete.Schema = modJsonType;
      incomplete.Type = SchemaDefinitionType;

      IncompleteSchemaDefinitionMap::iterator iter = m_incompleteDefinitions.find(globalType->missingReference);
      if (iter == m_incompleteDefinitions.end())
        m_incompleteDefinitions[globalType->missingReference] = std::vector<IncompleteSchemaDefinition>();

      CLog::Log(
          LOGINFO,
          "JSONRPC: Adding type \"{}\" to list of incomplete definitions (waiting for \"{}\")",
          typeName, globalType->missingReference);
      m_incompleteDefinitions[globalType->missingReference].push_back(incomplete);
    }

    globalType.reset();

    return false;
  }

  return true;
}

bool CJSONServiceDescription::AddMethod(const std::string &jsonMethod, MethodCall method)
{
  if (method == NULL)
  {
    CLog::Log(LOGERROR, "JSONRPC: Invalid JSONRPC method implementation");
    return false;
  }

  return addMethod(jsonMethod, method);
}

bool CJSONServiceDescription::AddBuiltinMethod(const std::string &jsonMethod)
{
  return addMethod(jsonMethod, NULL);
}

bool CJSONServiceDescription::AddNotification(const std::string &jsonNotification)
{
  CVariant descriptionObject;
  std::string notificationName;

  std::string modJsonNotification = jsonNotification;
  // Make sure the notification description actually exists and represents an object
  if (!prepareDescription(modJsonNotification, descriptionObject, notificationName))
  {
    CLog::Log(LOGERROR, "JSONRPC: Invalid JSON Schema definition for notification \"{}\"",
              notificationName);
    return false;
  }

  if (m_notifications.find(notificationName) != m_notifications.end())
  {
    CLog::Log(LOGERROR, "JSONRPC: There already is a notification with the name \"{}\"",
              notificationName);
    return false;
  }

  std::string type = GetString(descriptionObject[notificationName]["type"], "");
  if (type.compare("notification") != 0)
  {
    CLog::Log(LOGERROR, "JSONRPC: Invalid JSON type for notification \"{}\"", notificationName);
    return false;
  }

  m_notifications[notificationName] = descriptionObject;

  return true;
}

bool CJSONServiceDescription::AddEnum(const std::string &name, const std::vector<CVariant> &values, CVariant::VariantType type /* = CVariant::VariantTypeNull */, const CVariant &defaultValue /* = CVariant::ConstNullVariant */)
{
  if (name.empty() || m_types.find(name) != m_types.end() ||
      values.size() == 0)
    return false;

  JSONSchemaTypeDefinitionPtr definition = JSONSchemaTypeDefinitionPtr(new JSONSchemaTypeDefinition());
  definition->ID = name;

  std::vector<CVariant::VariantType> types;
  bool autoType = false;
  if (type == CVariant::VariantTypeNull)
    autoType = true;
  else
    types.push_back(type);

  for (unsigned int index = 0; index < values.size(); index++)
  {
    if (autoType)
      types.push_back(values[index].type());
    else if (type != CVariant::VariantTypeConstNull && type != values[index].type())
      return false;
  }
  definition->enums.insert(definition->enums.begin(), values.begin(), values.end());

  int schemaType = (int)AnyValue;
  for (unsigned int index = 0; index < types.size(); index++)
  {
    JSONSchemaType currentType;
    switch (type)
    {
      case CVariant::VariantTypeString:
        currentType = StringValue;
        break;
      case CVariant::VariantTypeDouble:
        currentType = NumberValue;
        break;
      case CVariant::VariantTypeInteger:
      case CVariant::VariantTypeUnsignedInteger:
        currentType = IntegerValue;
        break;
      case CVariant::VariantTypeBoolean:
        currentType = BooleanValue;
        break;
      case CVariant::VariantTypeArray:
        currentType = ArrayValue;
        break;
      case CVariant::VariantTypeObject:
        currentType = ObjectValue;
        break;
      case CVariant::VariantTypeConstNull:
        currentType = AnyValue;
        break;
      default:
      case CVariant::VariantTypeNull:
        return false;
    }

    if (index == 0)
      schemaType = currentType;
    else
      schemaType |= (int)currentType;
  }
  definition->type = (JSONSchemaType)schemaType;

  if (defaultValue.type() == CVariant::VariantTypeConstNull)
    definition->defaultValue = definition->enums.at(0);
  else
    definition->defaultValue = defaultValue;

  addReferenceTypeDefinition(definition);

  return true;
}

bool CJSONServiceDescription::AddEnum(const std::string &name, const std::vector<std::string> &values)
{
  std::vector<CVariant> enums;
  enums.reserve(values.size());
  for (const auto& it : values)
    enums.emplace_back(it);

  return AddEnum(name, enums, CVariant::VariantTypeString);
}

bool CJSONServiceDescription::AddEnum(const std::string &name, const std::vector<int> &values)
{
  std::vector<CVariant> enums;
  enums.reserve(values.size());
  for (const auto& it : values)
    enums.emplace_back(it);

  return AddEnum(name, enums, CVariant::VariantTypeInteger);
}

const char* CJSONServiceDescription::GetVersion()
{
  return JSONRPC_SERVICE_VERSION;
}

JSONRPC_STATUS CJSONServiceDescription::Print(CVariant &result, ITransportLayer *transport, IClient *client,
  bool printDescriptions /* = true */, bool printMetadata /* = false */, bool filterByTransport /* = true */,
  const std::string &filterByName /* = "" */, const std::string &filterByType /* = "" */, bool printReferences /* = true */)
{
  std::map<std::string, JSONSchemaTypeDefinitionPtr> types;
  CJsonRpcMethodMap methods;
  std::map<std::string, CVariant> notifications;

  int clientPermissions = client->GetPermissionFlags();
  int transportCapabilities = transport->GetCapabilities();

  if (filterByName.size() > 0)
  {
    std::string name = filterByName;

    if (filterByType == "method")
    {
      StringUtils::ToLower(name);

      CJsonRpcMethodMap::JsonRpcMethodIterator methodIterator = m_actionMap.find(name);
      if (methodIterator != m_actionMap.end() &&
         (clientPermissions & methodIterator->second.permission) == methodIterator->second.permission && ((transportCapabilities & methodIterator->second.transportneed) == methodIterator->second.transportneed || !filterByTransport))
        methods.add(methodIterator->second);
      else
        return InvalidParams;
    }
    else if (filterByType == "namespace")
    {
      // append a . delimiter to make sure we check for a namespace
      StringUtils::ToLower(name);
      name.append(".");

      CJsonRpcMethodMap::JsonRpcMethodIterator methodIterator;
      CJsonRpcMethodMap::JsonRpcMethodIterator methodIteratorEnd = m_actionMap.end();
      for (methodIterator = m_actionMap.begin(); methodIterator != methodIteratorEnd; methodIterator++)
      {
        // Check if the given name is at the very beginning of the method name
        if (methodIterator->first.find(name) == 0 &&
           (clientPermissions & methodIterator->second.permission) == methodIterator->second.permission && ((transportCapabilities & methodIterator->second.transportneed) == methodIterator->second.transportneed || !filterByTransport))
          methods.add(methodIterator->second);
      }

      if (methods.begin() == methods.end())
        return InvalidParams;
    }
    else if (filterByType == "type")
    {
      std::map<std::string, JSONSchemaTypeDefinitionPtr>::const_iterator typeIterator = m_types.find(name);
      if (typeIterator != m_types.end())
        types[typeIterator->first] = typeIterator->second;
      else
        return InvalidParams;
    }
    else if (filterByType == "notification")
    {
      std::map<std::string, CVariant>::const_iterator notificationIterator = m_notifications.find(name);
      if (notificationIterator != m_notifications.end())
        notifications[notificationIterator->first] = notificationIterator->second;
      else
        return InvalidParams;
    }
    else
      return InvalidParams;

    // If we need to print all referenced types we have to go through all parameters etc
    if (printReferences)
    {
      std::vector<std::string> referencedTypes;

      // Loop through all printed types to get all referenced types
      std::map<std::string, JSONSchemaTypeDefinitionPtr>::const_iterator typeIterator;
      std::map<std::string, JSONSchemaTypeDefinitionPtr>::const_iterator typeIteratorEnd = types.end();
      for (typeIterator = types.begin(); typeIterator != typeIteratorEnd; ++typeIterator)
        getReferencedTypes(typeIterator->second, referencedTypes);

      // Loop through all printed method's parameters and return value to get all referenced types
      CJsonRpcMethodMap::JsonRpcMethodIterator methodIterator;
      CJsonRpcMethodMap::JsonRpcMethodIterator methodIteratorEnd = methods.end();
      for (methodIterator = methods.begin(); methodIterator != methodIteratorEnd; methodIterator++)
      {
        for (unsigned int index = 0; index < methodIterator->second.parameters.size(); index++)
          getReferencedTypes(methodIterator->second.parameters.at(index), referencedTypes);

        getReferencedTypes(methodIterator->second.returns, referencedTypes);
      }

      for (unsigned int index = 0; index < referencedTypes.size(); index++)
      {
        std::map<std::string, JSONSchemaTypeDefinitionPtr>::const_iterator typeIterator = m_types.find(referencedTypes.at(index));
        if (typeIterator != m_types.end())
          types[typeIterator->first] = typeIterator->second;
      }
    }
  }
  else
  {
    types = m_types;
    methods = m_actionMap;
    notifications = m_notifications;
  }

  // Print the header
  result["id"] = JSONRPC_SERVICE_ID;
  result["version"] = JSONRPC_SERVICE_VERSION;
  result["description"] = JSONRPC_SERVICE_DESCRIPTION;

  std::map<std::string, JSONSchemaTypeDefinitionPtr>::const_iterator typeIterator;
  std::map<std::string, JSONSchemaTypeDefinitionPtr>::const_iterator typeIteratorEnd = types.end();
  for (typeIterator = types.begin(); typeIterator != typeIteratorEnd; ++typeIterator)
  {
    CVariant currentType = CVariant(CVariant::VariantTypeObject);
    typeIterator->second->Print(false, true, true, printDescriptions, currentType);

    result["types"][typeIterator->first] = currentType;
  }

  // Iterate through all json rpc methods
  CJsonRpcMethodMap::JsonRpcMethodIterator methodIterator;
  CJsonRpcMethodMap::JsonRpcMethodIterator methodIteratorEnd = methods.end();
  for (methodIterator = methods.begin(); methodIterator != methodIteratorEnd; methodIterator++)
  {
    if ((clientPermissions & methodIterator->second.permission) != methodIterator->second.permission || ((transportCapabilities & methodIterator->second.transportneed) != methodIterator->second.transportneed && filterByTransport))
      continue;

    CVariant currentMethod = CVariant(CVariant::VariantTypeObject);

    currentMethod["type"] = "method";
    if (printDescriptions && !methodIterator->second.description.empty())
      currentMethod["description"] = methodIterator->second.description;
    if (printMetadata)
    {
      CVariant permissions(CVariant::VariantTypeArray);
      for (int i = ReadData; i <= OPERATION_PERMISSION_ALL; i *= 2)
      {
        if ((methodIterator->second.permission & i) == i)
          permissions.push_back(PermissionToString((OperationPermission)i));
      }

      if (permissions.size() == 1)
        currentMethod["permission"] = permissions[0];
      else
        currentMethod["permission"] = permissions;
    }

    currentMethod["params"] = CVariant(CVariant::VariantTypeArray);
    for (unsigned int paramIndex = 0; paramIndex < methodIterator->second.parameters.size(); paramIndex++)
    {
      CVariant param = CVariant(CVariant::VariantTypeObject);
      methodIterator->second.parameters.at(paramIndex)->Print(true, false, true, printDescriptions, param);
      currentMethod["params"].append(param);
    }

    methodIterator->second.returns->Print(false, false, false, printDescriptions, currentMethod["returns"]);

    result["methods"][methodIterator->second.name] = currentMethod;
  }

  // Print notification description
  std::map<std::string, CVariant>::const_iterator notificationIterator;
  std::map<std::string, CVariant>::const_iterator notificationIteratorEnd = notifications.end();
  for (notificationIterator = notifications.begin(); notificationIterator != notificationIteratorEnd; ++notificationIterator)
    result["notifications"][notificationIterator->first] = notificationIterator->second[notificationIterator->first];

  return OK;
}

JSONRPC_STATUS CJSONServiceDescription::CheckCall(const char* const method, const CVariant &requestParameters, ITransportLayer *transport, IClient *client, bool notification, MethodCall &methodCall, CVariant &outputParameters)
{
  CJsonRpcMethodMap::JsonRpcMethodIterator iter = m_actionMap.find(method);
  if (iter != m_actionMap.end())
    return iter->second.Check(requestParameters, transport, client, notification, methodCall, outputParameters);

  return MethodNotFound;
}

JSONSchemaTypeDefinitionPtr CJSONServiceDescription::GetType(const std::string &identification)
{
  std::map<std::string, JSONSchemaTypeDefinitionPtr>::iterator iter = m_types.find(identification);
  if (iter == m_types.end())
    return JSONSchemaTypeDefinitionPtr();

  return iter->second;
}

bool CJSONServiceDescription::parseJSONSchemaType(const CVariant &value, std::vector<JSONSchemaTypeDefinitionPtr>& typeDefinitions, JSONSchemaType &schemaType, std::string &missingReference)
{
  missingReference.clear();
  schemaType = AnyValue;

  if (value.isArray())
  {
    int parsedType = 0;
    // If the defined type is an array, we have
    // to handle a union type
    for (unsigned int typeIndex = 0; typeIndex < value.size(); typeIndex++)
    {
      JSONSchemaTypeDefinitionPtr definition = JSONSchemaTypeDefinitionPtr(new JSONSchemaTypeDefinition());
      // If the type is a string try to parse it
      if (value[typeIndex].isString())
        definition->type = StringToSchemaValueType(value[typeIndex].asString());
      else if (value[typeIndex].isObject())
      {
        if (!definition->Parse(value[typeIndex]))
        {
          missingReference = definition->missingReference;
          CLog::Log(LOGERROR, "JSONRPC: Invalid type schema in union type definition");
          return false;
        }
      }
      else
      {
        CLog::Log(LOGWARNING, "JSONRPC: Invalid type in union type definition");
        return false;
      }

      definition->optional = false;
      typeDefinitions.push_back(definition);
      parsedType |= definition->type;
    }

    // If the type has not been set yet set it to "any"
    if (parsedType != 0)
      schemaType = (JSONSchemaType)parsedType;

    return true;
  }

  if (value.isString())
  {
    schemaType = StringToSchemaValueType(value.asString());
    return true;
  }

  return false;
}

void CJSONServiceDescription::addReferenceTypeDefinition(
    const JSONSchemaTypeDefinitionPtr& typeDefinition)
{
  // If the given json value is no object or does not contain an "id" field
  // of type string it is no valid type definition
  if (typeDefinition->ID.empty())
    return;

  // If the id has already been defined we ignore the type definition
  if (m_types.find(typeDefinition->ID) != m_types.end())
    return;

  // Add the type to the list of type definitions
  m_types[typeDefinition->ID] = typeDefinition;

  IncompleteSchemaDefinitionMap::iterator iter = m_incompleteDefinitions.find(typeDefinition->ID);
  if (iter == m_incompleteDefinitions.end())
    return;

  CLog::Log(LOGINFO, "JSONRPC: Resolving incomplete types/methods referencing {}",
            typeDefinition->ID);
  for (unsigned int index = 0; index < iter->second.size(); index++)
  {
    if (iter->second[index].Type == SchemaDefinitionType)
      AddType(iter->second[index].Schema);
    else
      AddMethod(iter->second[index].Schema, iter->second[index].Method);
  }

  m_incompleteDefinitions.erase(typeDefinition->ID);
}

void CJSONServiceDescription::removeReferenceTypeDefinition(const std::string &typeID)
{
  if (typeID.empty())
    return;

  std::map<std::string, JSONSchemaTypeDefinitionPtr>::iterator type = m_types.find(typeID);
  if (type != m_types.end())
    m_types.erase(type);
}

void CJSONServiceDescription::getReferencedTypes(const JSONSchemaTypeDefinitionPtr& type,
                                                 std::vector<std::string>& referencedTypes)
{
  // If the current type is a referenceable object, we can add it to the list
  if (type->ID.size() > 0)
  {
    for (unsigned int index = 0; index < referencedTypes.size(); index++)
    {
      // The referenceable object has already been added to the list so we can just skip it
      if (type->ID == referencedTypes.at(index))
        return;
    }

    referencedTypes.push_back(type->ID);
  }

  // If the current type is an object we need to check its properties
  if (HasType(type->type, ObjectValue))
  {
    JSONSchemaTypeDefinition::CJsonSchemaPropertiesMap::JSONSchemaPropertiesIterator iter;
    JSONSchemaTypeDefinition::CJsonSchemaPropertiesMap::JSONSchemaPropertiesIterator iterEnd = type->properties.end();
    for (iter = type->properties.begin(); iter != iterEnd; ++iter)
      getReferencedTypes(iter->second, referencedTypes);
  }
  // If the current type is an array we need to check its items
  if (HasType(type->type, ArrayValue))
  {
    unsigned int index;
    for (index = 0; index < type->items.size(); index++)
      getReferencedTypes(type->items.at(index), referencedTypes);

    for (index = 0; index < type->additionalItems.size(); index++)
      getReferencedTypes(type->additionalItems.at(index), referencedTypes);
  }

  // If the current type extends others type we need to check those types
  for (unsigned int index = 0; index < type->extends.size(); index++)
    getReferencedTypes(type->extends.at(index), referencedTypes);

  // If the current type is a union type we need to check those types
  for (unsigned int index = 0; index < type->unionTypes.size(); index++)
    getReferencedTypes(type->unionTypes.at(index), referencedTypes);
}

CJSONServiceDescription::CJsonRpcMethodMap::CJsonRpcMethodMap():
  m_actionmap(std::map<std::string, JsonRpcMethod>())
{
}

void CJSONServiceDescription::CJsonRpcMethodMap::clear()
{
  m_actionmap.clear();
}

void CJSONServiceDescription::CJsonRpcMethodMap::add(const JsonRpcMethod &method)
{
  std::string name = method.name;
  StringUtils::ToLower(name);
  m_actionmap[name] = method;
}

CJSONServiceDescription::CJsonRpcMethodMap::JsonRpcMethodIterator CJSONServiceDescription::CJsonRpcMethodMap::begin() const
{
  return m_actionmap.begin();
}

CJSONServiceDescription::CJsonRpcMethodMap::JsonRpcMethodIterator CJSONServiceDescription::CJsonRpcMethodMap::find(const std::string& key) const
{
  return m_actionmap.find(key);
}

CJSONServiceDescription::CJsonRpcMethodMap::JsonRpcMethodIterator CJSONServiceDescription::CJsonRpcMethodMap::end() const
{
  return m_actionmap.end();
}