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
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
//! Thing Description data structures
//!
//! A Thing Description, or `TD`, stores the semantic metadata and the interface descriptions of
//! a physical or virtual entity, called `Thing`.
//!
//! Use [Thing::builder] to build a new `Thing`, [serde_json] to serialize or deserialize it.
//!
//! [Interaction Affordance]: https://www.w3.org/TR/wot-thing-description/#interactionaffordance

use std::{
    borrow::Cow,
    cmp::{self, Ordering},
    collections::HashMap,
    fmt,
};

use oxilangtag::LanguageTag;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;
use serde_with::{serde_as, skip_serializing_none, DeserializeAs, OneOrMany, Same};
use time::OffsetDateTime;

use crate::{
    builder::{data_schema::UncheckedDataSchema, ThingBuilder, ToExtend},
    extend::ExtendableThing,
    hlist::Nil,
};

pub(crate) type MultiLanguage = HashMap<LanguageTag<String>, String>;
pub(crate) type DataSchemaMap<Other> = HashMap<
    String,
    DataSchema<
        <Other as ExtendableThing>::DataSchema,
        <Other as ExtendableThing>::ArraySchema,
        <Other as ExtendableThing>::ObjectSchema,
    >,
>;

/// The JSON-LD context for the version 1.0 of the [Thing
/// description](https://www.w3.org/TR/wot-thing-description/)
pub const TD_CONTEXT_10: &str = "https://www.w3.org/2019/wot/td/v1";

/// The JSON-LD context for the version 1.1 of the [Thing
/// description](https://www.w3.org/TR/wot-thing-description11/)
pub const TD_CONTEXT_11: &str = "https://www.w3.org/2022/wot/td/v1.1";

/// An abstraction of a physical or a virtual entity
///
/// It contains metadata and a description of its interfaces.
#[serde_as]
#[skip_serializing_none]
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Thing<Other: ExtendableThing = Nil> {
    // The context can be arbitrarily complex
    // https://www.w3.org/TR/json-ld11/#the-context
    // Let's take a value for now and assume we'll use the json-ld crate later
    /// A [JSON-LD @context](https://www.w3.org/TR/json-ld11/#the-context)
    #[serde(rename = "@context", default = "default_context")]
    pub context: Value,

    /// A unique identifier
    pub id: Option<String>,

    /// JSON-LD semantic keywords
    #[serde(rename = "@type", default)]
    #[serde_as(as = "Option<OneOrMany<_>>")]
    pub attype: Option<Vec<String>>,

    /// Human-readable title to be displayed
    pub title: String,

    /// Multi-language translations of the title
    pub titles: Option<MultiLanguage>,

    /// Human-readable additional information
    pub description: Option<String>,

    /// Multi-language translations of the description
    pub descriptions: Option<MultiLanguage>,

    /// Version information
    pub version: Option<VersionInfo>,

    /// Time of creation of this description
    ///
    /// It may be used for caching purposes.
    #[serde(with = "time::serde::rfc3339::option", default)]
    pub created: Option<OffsetDateTime>,

    /// Time of last update of this description
    ///
    /// It may be used for caching purposes.
    #[serde(with = "time::serde::rfc3339::option", default)]
    pub modified: Option<OffsetDateTime>,

    /// URI to the device maintainer
    ///
    /// To be used to ask for support.
    // FIXME: use AnyURI
    pub support: Option<String>,

    /// Base URI to be used to resolve all the other relative URIs
    ///
    /// NOTE: the JSON-LD @context is excluded.
    // FIXME: use AnyURI
    pub base: Option<String>,

    /// Property-based [Interaction Affordances]
    pub properties: Option<HashMap<String, PropertyAffordance<Other>>>,

    /// Action-based [Interaction Affordances]
    pub actions: Option<HashMap<String, ActionAffordance<Other>>>,

    /// Event-based [Interaction Affordances]
    pub events: Option<HashMap<String, EventAffordance<Other>>>,

    /// Arbitrary resources that relate to the current Thing
    ///
    /// Its meaning depends on the @context and the semantic attributes attached.
    pub links: Option<Vec<Link>>,

    /// Bulk-operations over the Thing properties
    pub forms: Option<Vec<Form<Other>>>,

    /// Thing-wide Security constraints
    ///
    /// It is a list of names matching the Security Schemes defined in [Thing::security_definitions].
    /// They must be all satisfied in order to access the Thing resources.
    #[serde_as(as = "OneOrMany<_>")]
    pub security: Vec<String>,

    /// Security definitions
    ///
    /// A Map of Security Schemes, the name keys are used in [Form::security] and [Thing::security]
    /// to express all the security constraints that must be satisfied in order to access the
    /// resources.
    pub security_definitions: HashMap<String, SecurityScheme>,

    /// URI template variables
    ///
    /// A Map of URI template variables that can be used inside `Forms`. The Thing level
    /// `uri_variables` can be used in Thing-level forms or in [`InteractionAffordance`]. The
    /// individual variables `DataSchema` cannot be an [`ObjectSchema`] or an [`ArraySchema`]. If
    /// the same variable is both declared in Thing-level `uri_variables` and in
    /// [`InteractionAffordance`] level, the `InteractionAffordance` level variable takes
    /// precedence.
    pub uri_variables: Option<DataSchemaMap<Other>>,

    /// The WoT profile
    ///
    /// Indicates the WoT Profile mechanisms followed by this Thing Description and the
    /// corresponding Thing implementation.
    #[serde(default)]
    #[serde_as(as = "Option<OneOrMany<_>>")]
    pub profile: Option<Vec<String>>,

    /// A Map of named data schemas
    ///
    /// To be used in a schema name-value pair inside an [`AdditionalExpectedResponse`] object.
    pub schema_definitions: Option<DataSchemaMap<Other>>,

    /// Thing extension
    #[serde(flatten)]
    pub other: Other,
}

impl<Other> fmt::Debug for Thing<Other>
where
    Other: ExtendableThing + fmt::Debug,
    PropertyAffordance<Other>: fmt::Debug,
    ActionAffordance<Other>: fmt::Debug,
    EventAffordance<Other>: fmt::Debug,
    Form<Other>: fmt::Debug,
    DataSchemaFromOther<Other>: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Thing")
            .field("context", &self.context)
            .field("id", &self.id)
            .field("attype", &self.attype)
            .field("title", &self.title)
            .field("titles", &self.titles)
            .field("description", &self.description)
            .field("descriptions", &self.descriptions)
            .field("version", &self.version)
            .field("created", &self.created)
            .field("modified", &self.modified)
            .field("support", &self.support)
            .field("base", &self.base)
            .field("properties", &self.properties)
            .field("actions", &self.actions)
            .field("events", &self.events)
            .field("links", &self.links)
            .field("forms", &self.forms)
            .field("security", &self.security)
            .field("security_definitions", &self.security_definitions)
            .field("uri_variables", &self.uri_variables)
            .field("profile", &self.profile)
            .field("schema_definitions", &self.schema_definitions)
            .field("other", &self.other)
            .finish()
    }
}

impl<Other> Default for Thing<Other>
where
    Other: ExtendableThing + Default,
{
    fn default() -> Self {
        Self {
            context: Default::default(),
            id: Default::default(),
            attype: Default::default(),
            title: Default::default(),
            titles: Default::default(),
            description: Default::default(),
            descriptions: Default::default(),
            version: Default::default(),
            created: Default::default(),
            modified: Default::default(),
            support: Default::default(),
            base: Default::default(),
            properties: Default::default(),
            actions: Default::default(),
            events: Default::default(),
            links: Default::default(),
            forms: Default::default(),
            security: Default::default(),
            security_definitions: Default::default(),
            uri_variables: Default::default(),
            profile: Default::default(),
            schema_definitions: Default::default(),
            other: Default::default(),
        }
    }
}

impl<Other> PartialEq for Thing<Other>
where
    Other: ExtendableThing + PartialEq,
    Form<Other>: PartialEq,
    PropertyAffordance<Other>: PartialEq,
    ActionAffordance<Other>: PartialEq,
    EventAffordance<Other>: PartialEq,
    DataSchemaFromOther<Other>: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.context == other.context
            && self.id == other.id
            && self.attype == other.attype
            && self.title == other.title
            && self.titles == other.titles
            && self.description == other.description
            && self.descriptions == other.descriptions
            && self.version == other.version
            && self.created == other.created
            && self.modified == other.modified
            && self.support == other.support
            && self.base == other.base
            && self.properties == other.properties
            && self.actions == other.actions
            && self.events == other.events
            && self.links == other.links
            && self.forms == other.forms
            && self.security == other.security
            && self.security_definitions == other.security_definitions
            && self.uri_variables == other.uri_variables
            && self.profile == other.profile
            && self.schema_definitions == other.schema_definitions
            && self.other == other.other
    }
}

fn default_context() -> Value {
    TD_CONTEXT_11.into()
}

impl Thing<Nil> {
    /// Shorthand for [ThingBuilder::new].
    #[inline]
    pub fn builder(title: impl Into<String>) -> ThingBuilder<Nil, ToExtend> {
        ThingBuilder::new(title)
    }
}

/// Thing description Interaction Affordance
///
/// Metadata of a Thing that shows the possible choices to Consumers, thereby suggesting how
/// Consumers may interact with the Thing. See [w3c
/// documentation](https://www.w3.org/TR/wot-thing-description11/#interactionaffordance) for
/// further details.
#[serde_as]
#[skip_serializing_none]
#[derive(Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct InteractionAffordance<Other: ExtendableThing> {
    /// JSON-LD keyword to label the object with semantic tags or types.
    #[serde(rename = "@type", default)]
    #[serde_as(as = "Option<OneOrMany<_>>")]
    pub attype: Option<Vec<String>>,

    /// A human-readable title based on a default language.
    pub title: Option<String>,

    /// Multi-language human-readable titles.
    pub titles: Option<MultiLanguage>,

    /// Additional human-readable information based on a default language.
    pub description: Option<String>,

    /// Additional human-readable information in different languages.
    pub descriptions: Option<MultiLanguage>,

    /// Set of form hypermedia controls that describe how an operation can be performed.
    pub forms: Vec<Form<Other>>,

    /// URI template variables
    ///
    /// A Map of URI template variables that can be used inside `Forms`. The individual variables
    /// `DataSchema` cannot be an [`ObjectSchema`] or an [`ArraySchema`]. If the same variable is
    /// both declared in [`Thing`]-level `uri_variables` and in `InteractionAffordance` level, the
    /// `InteractionAffordance` level variable takes precedence.
    pub uri_variables: Option<DataSchemaMap<Other>>,

    /// Interaction affordance extension
    #[serde(flatten)]
    pub other: Other::InteractionAffordance,
}

impl<Other> fmt::Debug for InteractionAffordance<Other>
where
    Other: ExtendableThing,
    Form<Other>: fmt::Debug,
    DataSchemaFromOther<Other>: fmt::Debug,
    Other::InteractionAffordance: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("InteractionAffordance")
            .field("attype", &self.attype)
            .field("title", &self.title)
            .field("titles", &self.titles)
            .field("description", &self.description)
            .field("descriptions", &self.descriptions)
            .field("forms", &self.forms)
            .field("uri_variables", &self.uri_variables)
            .field("other", &self.other)
            .finish()
    }
}

impl<Other> Default for InteractionAffordance<Other>
where
    Other: ExtendableThing,
    Form<Other>: Default,
    DataSchemaFromOther<Other>: Default,
    Other::InteractionAffordance: Default,
{
    fn default() -> Self {
        Self {
            attype: Default::default(),
            title: Default::default(),
            titles: Default::default(),
            description: Default::default(),
            descriptions: Default::default(),
            forms: Default::default(),
            uri_variables: Default::default(),
            other: Default::default(),
        }
    }
}

impl<Other> PartialEq for InteractionAffordance<Other>
where
    Other: ExtendableThing,
    Form<Other>: PartialEq,
    DataSchemaFromOther<Other>: PartialEq,
    Other::InteractionAffordance: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.attype == other.attype
            && self.title == other.title
            && self.titles == other.titles
            && self.description == other.description
            && self.descriptions == other.descriptions
            && self.forms == other.forms
            && self.uri_variables == other.uri_variables
            && self.other == other.other
    }
}

/// An affordance that exposes the state of a `Thing`
#[skip_serializing_none]
#[derive(Deserialize, Serialize)]
pub struct PropertyAffordance<Other: ExtendableThing> {
    /// The interaction affordance.
    #[serde(flatten)]
    pub interaction: InteractionAffordance<Other>,

    /// The data schema representing the property.
    #[serde(flatten)]
    pub data_schema: DataSchemaFromOther<Other>,

    /// A hint that indicates whether Servients hosting the Thing and Intermediaries should provide
    /// a Protocol Binding that supports the [`ObserveProperty`] and [`UnobserveProperty`]
    /// operations for this property.
    ///
    /// [`ObserveProperty`]: FormOperation::ObserveProperty
    /// [`UnobserveProperty`]: FormOperation::UnobserveProperty
    pub observable: Option<bool>,

    /// Property affordance extension.
    #[serde(flatten)]
    pub other: Other::PropertyAffordance,
}

impl<Other> fmt::Debug for PropertyAffordance<Other>
where
    Other: ExtendableThing,
    InteractionAffordance<Other>: fmt::Debug,
    DataSchemaFromOther<Other>: fmt::Debug,
    Other::PropertyAffordance: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PropertyAffordance")
            .field("interaction", &self.interaction)
            .field("data_schema", &self.data_schema)
            .field("observable", &self.observable)
            .field("other", &self.other)
            .finish()
    }
}

impl<Other> Default for PropertyAffordance<Other>
where
    Other: ExtendableThing,
    InteractionAffordance<Other>: Default,
    DataSchemaFromOther<Other>: Default,
    Other::PropertyAffordance: Default,
{
    fn default() -> Self {
        Self {
            interaction: Default::default(),
            data_schema: Default::default(),
            observable: Default::default(),
            other: Default::default(),
        }
    }
}

impl<Other> PartialEq for PropertyAffordance<Other>
where
    Other: ExtendableThing,
    InteractionAffordance<Other>: PartialEq,
    DataSchemaFromOther<Other>: PartialEq,
    Other::PropertyAffordance: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.interaction == other.interaction
            && self.data_schema == other.data_schema
            && self.observable == other.observable
            && self.other == other.other
    }
}

/// An affordance that allows to inkvoke a function of the `Thing`.
#[skip_serializing_none]
#[derive(Deserialize, Serialize)]
pub struct ActionAffordance<Other: ExtendableThing> {
    /// The interaction affordance.
    #[serde(flatten)]
    pub interaction: InteractionAffordance<Other>,

    /// The input data schema of the action.
    pub input: Option<DataSchemaFromOther<Other>>,

    /// The output data schema of the action.
    pub output: Option<DataSchemaFromOther<Other>>,

    /// Whether the action is safe or not.
    ///
    /// In case it is `true`, when the action is invoked there is no internal state that is being
    /// changed.
    #[serde(default)]
    pub safe: bool,

    /// Whether the action is idempotent or not.
    ///
    /// In case it is `true`, the action can be called repeatedly with the same result based on the
    /// same input.
    #[serde(default)]
    pub idempotent: bool,

    /// Whether the action is synchronous or not.
    ///
    /// A synchronous action means that the response of action contains all the information about
    /// the result of the action and no further querying about the status of the action is needed.
    ///
    /// If this is `None`, no claim on the synchronicity of the action can be made.
    pub synchronous: Option<bool>,

    /// Action affordance extension
    #[serde(flatten)]
    pub other: Other::ActionAffordance,
}

impl<Other> fmt::Debug for ActionAffordance<Other>
where
    Other: ExtendableThing,
    InteractionAffordance<Other>: fmt::Debug,
    DataSchemaFromOther<Other>: fmt::Debug,
    Other::ActionAffordance: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("ActionAffordance")
            .field("interaction", &self.interaction)
            .field("input", &self.input)
            .field("output", &self.output)
            .field("safe", &self.safe)
            .field("idempotent", &self.idempotent)
            .field("synchronous", &self.synchronous)
            .field("other", &self.other)
            .finish()
    }
}

impl<Other> Default for ActionAffordance<Other>
where
    Other: ExtendableThing,
    InteractionAffordance<Other>: Default,
    DataSchemaFromOther<Other>: Default,
    Other::ActionAffordance: Default,
{
    fn default() -> Self {
        Self {
            interaction: Default::default(),
            input: Default::default(),
            output: Default::default(),
            safe: Default::default(),
            idempotent: Default::default(),
            synchronous: Default::default(),
            other: Default::default(),
        }
    }
}

impl<Other> PartialEq for ActionAffordance<Other>
where
    Other: ExtendableThing,
    InteractionAffordance<Other>: PartialEq,
    DataSchemaFromOther<Other>: PartialEq,
    Other::ActionAffordance: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.interaction == other.interaction
            && self.input == other.input
            && self.output == other.output
            && self.safe == other.safe
            && self.idempotent == other.idempotent
            && self.synchronous == other.synchronous
            && self.other == other.other
    }
}

/// An affordance that describes an event source.
#[skip_serializing_none]
#[derive(Deserialize, Serialize)]
pub struct EventAffordance<Other: ExtendableThing> {
    /// The interaction affordance.
    #[serde(flatten)]
    pub interaction: InteractionAffordance<Other>,

    /// Data that needs to be passed upon subscription.
    pub subscription: Option<DataSchemaFromOther<Other>>,

    /// Data schema of the messages pushed by the `Thing`.
    pub data: Option<DataSchemaFromOther<Other>>,

    /// Data schema of the responsed messages sent by the consumer in a response to a data message.
    pub data_response: Option<DataSchemaFromOther<Other>>,

    /// Data that needs to be passed to cancel a subscription.
    pub cancellation: Option<DataSchemaFromOther<Other>>,

    /// Event affordance extension.
    #[serde(flatten)]
    pub other: Other::EventAffordance,
}

impl<Other> fmt::Debug for EventAffordance<Other>
where
    Other: ExtendableThing,
    InteractionAffordance<Other>: fmt::Debug,
    DataSchemaFromOther<Other>: fmt::Debug,
    Other::EventAffordance: fmt::Debug,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("EventAffordance")
            .field("interaction", &self.interaction)
            .field("subscription", &self.subscription)
            .field("data", &self.data)
            .field("data_response", &self.data_response)
            .field("cancellation", &self.cancellation)
            .field("other", &self.other)
            .finish()
    }
}

impl<Other> Default for EventAffordance<Other>
where
    Other: ExtendableThing,
    InteractionAffordance<Other>: Default,
    DataSchemaFromOther<Other>: Default,
    Other::EventAffordance: Default,
{
    fn default() -> Self {
        Self {
            interaction: Default::default(),
            subscription: Default::default(),
            data: Default::default(),
            data_response: Default::default(),
            cancellation: Default::default(),
            other: Default::default(),
        }
    }
}

impl<Other> PartialEq for EventAffordance<Other>
where
    Other: ExtendableThing,
    InteractionAffordance<Other>: PartialEq,
    DataSchemaFromOther<Other>: PartialEq,
    Other::EventAffordance: PartialEq,
{
    fn eq(&self, other: &Self) -> bool {
        self.interaction == other.interaction
            && self.subscription == other.subscription
            && self.data == other.data
            && self.data_response == other.data_response
            && self.cancellation == other.cancellation
            && self.other == other.other
    }
}

/// Metadata of a `Thing` that provides version information about the _Thing Description_ document.
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub struct VersionInfo {
    /// The version indicator of this _Thing Description_ instance.
    pub instance: String,

    /// The version indicator of the underlying _Thing Model_.
    pub model: Option<String>,
}

impl<S> From<S> for VersionInfo
where
    S: Into<String>,
{
    fn from(instance: S) -> Self {
        let instance = instance.into();
        Self {
            instance,
            model: None,
        }
    }
}

/// Metadata that describes the data format used.
#[serde_as]
#[skip_serializing_none]
#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DataSchema<DS, AS, OS> {
    /// JSON-LD keyword to label the object with semantic tags or types.
    #[serde(rename = "@type", default)]
    #[serde_as(as = "Option<OneOrMany<_>>")]
    pub attype: Option<Vec<String>>,

    /// Human-readable title to be displayed
    pub title: Option<String>,

    /// Multi-language translations of the title
    pub titles: Option<MultiLanguage>,

    /// Human-readable additional information
    pub description: Option<String>,

    /// Multi-language translations of the description
    pub descriptions: Option<MultiLanguage>,

    /// A constant value for the data schema.
    #[serde(rename = "const")]
    pub constant: Option<Value>,

    /// A default value for the data schema.
    pub default: Option<Value>,

    /// Unit information used for the data schema (e.g. Km, g, m/s^2)
    pub unit: Option<String>,

    /// Used to ensure that the data is valid against one of the specified schemas.
    pub one_of: Option<Vec<Self>>,

    /// A restricted set of values.
    #[serde(rename = "enum")]
    pub enumeration: Option<Vec<Value>>,

    /// Indicates if the property interaction value is read only.
    #[serde(default)]
    pub read_only: bool,

    /// Indicates if the property interaction value is write only.
    #[serde(default)]
    pub write_only: bool,

    /// Allows validation based on a format pattern such as "date-time", "email", "uri".
    pub format: Option<String>,

    /// The JSON-based subtype of the data schema.
    #[serde(flatten)]
    pub subtype: Option<DataSchemaSubtype<DS, AS, OS>>,

    /// Data schema extension.
    #[serde(flatten)]
    pub other: DS,
}

pub(crate) type DataSchemaFromOther<Other> = DataSchema<
    <Other as ExtendableThing>::DataSchema,
    <Other as ExtendableThing>::ArraySchema,
    <Other as ExtendableThing>::ObjectSchema,
>;

/// A JSON-based data schema subtype.
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
#[serde(tag = "type", rename_all = "lowercase")]
pub enum DataSchemaSubtype<DS, AS, OS> {
    /// A JSON array metadata.
    Array(ArraySchema<DS, AS, OS>),

    /// A boolean.
    Boolean,

    /// A number metadata.
    Number(NumberSchema),

    /// An integer metadata.
    Integer(IntegerSchema),

    /// A JSON object metadata.
    Object(ObjectSchema<DS, AS, OS>),

    /// A string metadata.
    String(StringSchema),

    /// A JSON null.
    Null,
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) enum UncheckedDataSchemaSubtype<DS, AS, OS> {
    Array(UncheckedArraySchema<DS, AS, OS>),
    Boolean,
    Number(NumberSchema),
    Integer(IntegerSchema),
    Object(UncheckedObjectSchema<DS, AS, OS>),
    String(StringSchema),
    Null,
}

impl<DS, AS, OS> Default for DataSchemaSubtype<DS, AS, OS> {
    fn default() -> Self {
        Self::Null
    }
}

/// A JSON array metadata.
#[serde_as]
#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
#[serde(bound(
    deserialize = "DS: Deserialize<'de>, AS: Deserialize<'de>, OS: Deserialize<'de>",
    serialize = "DS: Serialize, AS: Serialize, OS: Serialize"
))]
pub struct ArraySchema<DS, AS, OS> {
    /// The characteristics of the JSON array.
    #[serde(default)]
    #[serde_as(as = "Option<OneOrMany<_>>")]
    pub items: Option<Vec<DataSchema<DS, AS, OS>>>,

    /// The minimum number of items that have to be in the JSON array.
    pub min_items: Option<u32>,

    /// The maximum number of items that have to be in the JSON array.
    pub max_items: Option<u32>,

    /// Array schema extension.
    #[serde(flatten)]
    pub other: AS,
}

#[derive(Clone, Debug, Default, PartialEq)]
pub(crate) struct UncheckedArraySchema<DS, AS, OS> {
    pub(crate) items: Option<Vec<UncheckedDataSchema<DS, AS, OS>>>,
    pub(crate) min_items: Option<u32>,
    pub(crate) max_items: Option<u32>,
    pub(crate) other: AS,
}

impl<DS, AS, OS> Default for ArraySchema<DS, AS, OS>
where
    AS: Default,
{
    fn default() -> Self {
        Self {
            items: Default::default(),
            min_items: Default::default(),
            max_items: Default::default(),
            other: Default::default(),
        }
    }
}

/// A helper enum to represent an inclusive or exclusive maximum value.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
pub enum Maximum<T> {
    /// An inclusive maximum value.
    #[serde(rename = "maximum")]
    Inclusive(T),

    /// An exclusive maximum value.
    #[serde(rename = "exclusiveMaximum")]
    Exclusive(T),
}

/// A helper enum to represent an inclusive or exclusive minimum value.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
pub enum Minimum<T> {
    /// An inclusive minimum value.
    #[serde(rename = "minimum")]
    Inclusive(T),

    /// An exclusive minimum value.
    #[serde(rename = "exclusiveMinimum")]
    Exclusive(T),
}

impl<T> PartialOrd for Minimum<T>
where
    T: PartialOrd,
{
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<cmp::Ordering> {
        match (self, other) {
            (Minimum::Inclusive(a), Minimum::Inclusive(b))
            | (Minimum::Exclusive(a), Minimum::Exclusive(b)) => a.partial_cmp(b),
            (Minimum::Inclusive(a), Minimum::Exclusive(b)) => {
                a.partial_cmp(b).and_then(|ord| match ord {
                    Ordering::Less | Ordering::Equal => Some(Ordering::Less),
                    Ordering::Greater => None,
                })
            }
            (Minimum::Exclusive(a), Minimum::Inclusive(b)) => {
                a.partial_cmp(b).and_then(|ord| match ord {
                    Ordering::Less => None,
                    Ordering::Equal | Ordering::Greater => Some(Ordering::Greater),
                })
            }
        }
    }
}

impl<T> PartialOrd for Maximum<T>
where
    T: PartialOrd,
{
    #[inline]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        match (self, other) {
            (Maximum::Inclusive(a), Maximum::Inclusive(b))
            | (Maximum::Exclusive(a), Maximum::Exclusive(b)) => a.partial_cmp(b),

            (Maximum::Inclusive(a), Maximum::Exclusive(b)) => {
                a.partial_cmp(b).and_then(|ord| match ord {
                    Ordering::Less => None,
                    Ordering::Equal | Ordering::Greater => Some(Ordering::Greater),
                })
            }

            (Maximum::Exclusive(a), Maximum::Inclusive(b)) => {
                a.partial_cmp(b).and_then(|ord| match ord {
                    Ordering::Less | Ordering::Equal => Some(Ordering::Less),
                    Ordering::Greater => None,
                })
            }
        }
    }
}

impl<T> PartialEq<Maximum<T>> for Minimum<T>
where
    T: PartialEq,
{
    #[inline]
    fn eq(&self, other: &Maximum<T>) -> bool {
        match (self, other) {
            (Minimum::Inclusive(a), Maximum::Inclusive(b))
            | (Minimum::Exclusive(a), Maximum::Exclusive(b)) => a == b,
            _ => false,
        }
    }
}

impl<T> PartialEq<Minimum<T>> for Maximum<T>
where
    T: PartialEq,
{
    #[inline]
    fn eq(&self, other: &Minimum<T>) -> bool {
        other == self
    }
}

impl<T> PartialOrd<Maximum<T>> for Minimum<T>
where
    T: PartialOrd,
{
    #[inline]
    fn partial_cmp(&self, other: &Maximum<T>) -> Option<cmp::Ordering> {
        match (self, other) {
            (Minimum::Inclusive(a), Maximum::Inclusive(b))
            | (Minimum::Exclusive(a), Maximum::Exclusive(b)) => a.partial_cmp(b),

            (Minimum::Exclusive(a), Maximum::Inclusive(b))
            | (Minimum::Inclusive(a), Maximum::Exclusive(b)) => {
                a.partial_cmp(b).and_then(|ord| match ord {
                    Ordering::Less => None,
                    Ordering::Equal | Ordering::Greater => Some(Ordering::Greater),
                })
            }
        }
    }
}

impl<T> PartialOrd<Minimum<T>> for Maximum<T>
where
    T: PartialOrd,
{
    #[inline]
    fn partial_cmp(&self, other: &Minimum<T>) -> Option<Ordering> {
        other.partial_cmp(self).map(Ordering::reverse)
    }
}

macro_rules! impl_minmax_float {
    (@ $ty:ident $float_type:ty) => {
        impl $ty<$float_type> {
            /// Returns `true` if value is `NaN`.
            pub fn is_nan(&self) -> bool {
                match self {
                    Self::Inclusive(x) => x.is_nan(),
                    Self::Exclusive(x) => x.is_nan(),
                }
            }
        }
    };

    ($($float_type:ty),*) => {
        $(
            impl_minmax_float!(@ Minimum $float_type);
            impl_minmax_float!(@ Maximum $float_type);
        )*
    };
}

impl_minmax_float!(f32, f64);

/// A number metadata.
#[skip_serializing_none]
#[derive(Clone, Debug, Default, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct NumberSchema {
    /// The higher limit of the value.
    #[serde(flatten)]
    pub maximum: Option<Maximum<f64>>,

    /// The lower limit of the value.
    #[serde(flatten)]
    pub minimum: Option<Minimum<f64>>,

    /// It adds the requirement that the numeric value must be a multiple of this.
    pub multiple_of: Option<f64>,
}

/// An integer metadata.
#[skip_serializing_none]
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
// FIXME: we should probably use a Decimal type
pub struct IntegerSchema {
    /// The higher limit of the value.
    #[serde(flatten)]
    pub maximum: Option<Maximum<usize>>,

    /// The lower limit of the value.
    #[serde(flatten)]
    pub minimum: Option<Minimum<usize>>,

    /// It adds the requirement that the numeric value must be a multiple of this.
    pub multiple_of: Option<usize>,
}

/// A JSON object metadata.
#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct ObjectSchema<DS, AS, OS> {
    /// Data schema nested definitions.
    pub properties: Option<HashMap<String, DataSchema<DS, AS, OS>>>,

    /// Defines which members of the object type are mandatory.
    pub required: Option<Vec<String>>,

    /// Object schema extension.
    #[serde(flatten)]
    pub other: OS,
}

#[derive(Clone, Debug, PartialEq)]
pub(crate) struct UncheckedObjectSchema<DS, AS, OS> {
    pub(crate) properties: Option<HashMap<String, UncheckedDataSchema<DS, AS, OS>>>,
    pub(crate) required: Option<Vec<String>>,
    pub(crate) other: OS,
}

impl<DS, AS, OS> Default for ObjectSchema<DS, AS, OS>
where
    OS: Default,
{
    fn default() -> Self {
        Self {
            properties: Default::default(),
            required: Default::default(),
            other: Default::default(),
        }
    }
}

impl<DS, AS, OS> Default for UncheckedObjectSchema<DS, AS, OS>
where
    OS: Default,
{
    fn default() -> Self {
        Self {
            properties: Default::default(),
            required: Default::default(),
            other: Default::default(),
        }
    }
}

/// A string metadata
#[skip_serializing_none]
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StringSchema {
    /// The minimum length of a string.
    pub min_length: Option<u32>,

    /// The maximum length of a string.
    pub max_length: Option<u32>,

    /// A regular expression to express constraints of the string value. The regular expression
    /// must follow the [ECMA-262](https://www.w3.org/TR/wot-thing-description11/#bib-ecma-262)
    /// dialect.
    // TODO: this should be a validated against EcmaScript dialect of regexes
    pub pattern: Option<String>,

    /// The encoding used to store the contents, as specified in [RFC
    /// 2045](https://www.rfc-editor.org/rfc/rfc2045).
    // TODO: this should be validated against RFC 2045
    pub content_encoding: Option<String>,

    /// the MIME type of the contents of a string value, as described in [RFC
    /// 2046](https://www.rfc-editor.org/rfc/rfc2046).
    // TODO: this should be validated against RFC 2046
    pub content_media_type: Option<String>,
}

/// The configuration of a security mechanism.
#[serde_as]
#[skip_serializing_none]
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct SecurityScheme {
    /// JSON-LD keyword to label the object with semantic tags or types.
    #[serde(rename = "@type", default)]
    #[serde_as(as = "Option<OneOrMany<_>>")]
    pub attype: Option<Vec<String>>,

    /// Human-readable additional information
    pub description: Option<String>,

    /// Multi-language translations of the description
    pub descriptions: Option<MultiLanguage>,

    /// URI of the proxy server this security configuration provides access to. If `None`, the
    /// corresponding security configuration is for the endpoint.
    // FIXME: use AnyURI
    pub proxy: Option<String>,

    /// The security scheme subtype.
    #[serde(flatten)]
    pub subtype: SecuritySchemeSubtype,
}

/// A pre-defined security scheme subtype.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[serde(tag = "scheme", rename_all = "lowercase")]
pub enum KnownSecuritySchemeSubtype {
    /// No authentication or other mechanism required to access the resource.
    #[default]
    NoSec,

    /// The security parameters are going to be negotiated by the underlying protocols at runtime.
    Auto,

    /// A combination of security schemes.
    Combo(ComboSecurityScheme),

    /// Basic Authentication ([RFC7617](https://httpwg.org/specs/rfc7617.html)) security
    /// configuration
    Basic(BasicSecurityScheme),

    /// Digest Access Authentication ([RFC7616](https://httpwg.org/specs/rfc7616.html)) security
    /// configuration
    Digest(DigestSecurityScheme),

    /// Bearer Token ([RFC6750](https://www.rfc-editor.org/rfc/rfc6750)) security configuration
    Bearer(BearerSecurityScheme),

    /// Pre-shared key authentication security configuration.
    Psk(PskSecurityScheme),

    /// OAuth 2.0 authentication security configuration for systems conformant with
    /// [RFC6749](https://www.rfc-editor.org/rfc/rfc6749),
    /// [RFC8252](https://www.rfc-editor.org/rfc/rfc8252) and (for the device flow)
    /// [RFC8628](https://www.rfc-editor.org/rfc/rfc8628)
    OAuth2(OAuth2SecurityScheme),

    /// API key authentication security configuration.
    ApiKey(ApiKeySecurityScheme),
}

/// Custom security scheme subtype
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
pub struct UnknownSecuritySchemeSubtype {
    /// The name of the security scheme.
    pub scheme: String,

    /// The inner data of the security scheme.
    #[serde(flatten)]
    pub data: Value,
}

/// A security scheme subtype.
#[derive(Clone, Debug, PartialEq, Eq, Deserialize, Serialize)]
#[serde(untagged)]
pub enum SecuritySchemeSubtype {
    /// Pre-defined security scheme subtype.
    Known(KnownSecuritySchemeSubtype),

    /// Custom security scheme subtype
    Unknown(UnknownSecuritySchemeSubtype),
}

impl Default for SecuritySchemeSubtype {
    fn default() -> Self {
        Self::Known(KnownSecuritySchemeSubtype::default())
    }
}

/// A combination of security schemes.
#[serde_as]
#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum ComboSecurityScheme {
    /// Two or more strings identifying other named security scheme definitions, any one of which,
    /// when satisfied, will allow access.
    OneOf(#[serde_as(as = "OneOrMany<_>")] Vec<String>),

    /// Two or more strings identifying other named security scheme definitions, all of which must
    /// be satisfied for access.
    AllOf(#[serde_as(as = "OneOrMany<_>")] Vec<String>),
}

/// Basic Authentication ([RFC7617](https://httpwg.org/specs/rfc7617.html)) security configuration
#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub struct BasicSecurityScheme {
    /// The location of security authentication information.
    #[serde(rename = "in", default = "SecurityAuthenticationLocation::header")]
    pub location: SecurityAuthenticationLocation,

    /// Name for query, header, cookie, or uri parameters.
    pub name: Option<String>,
}

impl Default for BasicSecurityScheme {
    fn default() -> Self {
        Self {
            location: SecurityAuthenticationLocation::Header,
            name: Default::default(),
        }
    }
}

/// The location of security authentication information.
#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum SecurityAuthenticationLocation {
    /// The parameter will be given in a header provided by the protocol, with the name of the
    /// header provided by the value of `name`.
    Header,

    /// The parameter will be appended to the URI as a query parameter, with the name of the query
    /// parameter provided by `name`.
    Query,

    /// The parameter will be provided in the body of the request payload, with the data schema
    /// element used provided by `name`.
    Body,

    /// The parameter is stored in a cookie identified by the value of `name`.
    Cookie,

    /// The parameter is embedded in the URI itself, which is encoded in the relevant interaction
    /// using a URI template variable defined by the value of `name`.
    Uri,
}

impl SecurityAuthenticationLocation {
    const fn header() -> Self {
        Self::Header
    }

    const fn query() -> Self {
        Self::Query
    }
}

/// Digest Access Authentication ([RFC7616](https://httpwg.org/specs/rfc7616.html)) security configuration
#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub struct DigestSecurityScheme {
    /// Quality of protection.
    pub qop: QualityOfProtection,

    /// The location of security authentication information.
    #[serde(rename = "in", default = "SecurityAuthenticationLocation::header")]
    pub location: SecurityAuthenticationLocation,

    /// Name for query, header, cookie, or uri parameters.
    pub name: Option<String>,
}

impl Default for DigestSecurityScheme {
    fn default() -> Self {
        Self {
            qop: Default::default(),
            location: SecurityAuthenticationLocation::Header,
            name: Default::default(),
        }
    }
}

/// Quality of protection, as defined in [RFC2617](https://www.rfc-editor.org/rfc/rfc2617).
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub enum QualityOfProtection {
    /// Protection by authentication.
    #[default]
    Auth,

    /// Protection by authentication with integrity protection.
    AuthInt,
}

/// API key authentication security configuration.
#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub struct ApiKeySecurityScheme {
    /// The location of security authentication information.
    #[serde(rename = "in", default = "SecurityAuthenticationLocation::query")]
    pub location: SecurityAuthenticationLocation,

    /// Name for query, header, cookie, or uri parameters.
    pub name: Option<String>,
}

impl Default for ApiKeySecurityScheme {
    fn default() -> Self {
        Self {
            location: SecurityAuthenticationLocation::Query,
            name: Default::default(),
        }
    }
}

/// Pre-shared key authentication security configuration.
#[skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub struct BearerSecurityScheme {
    /// URI of the authorization server.
    // FIXME: use AnyURI
    pub authorization: Option<String>,

    /// Encoding, encryption, or digest algorithm.
    #[serde(default = "BearerSecurityScheme::default_alg")]
    pub alg: Cow<'static, str>,

    /// Format of security authentication information.
    #[serde(default = "BearerSecurityScheme::default_format")]
    pub format: Cow<'static, str>,

    /// The location of security authentication information.
    #[serde(rename = "in", default = "SecurityAuthenticationLocation::header")]
    pub location: SecurityAuthenticationLocation,

    /// Name for query, header, cookie, or uri parameters.
    pub name: Option<String>,
}

impl Default for BearerSecurityScheme {
    fn default() -> Self {
        Self {
            authorization: Default::default(),
            alg: BearerSecurityScheme::default_alg(),
            format: BearerSecurityScheme::default_format(),
            location: SecurityAuthenticationLocation::Header,
            name: Default::default(),
        }
    }
}

impl BearerSecurityScheme {
    const fn default_alg() -> Cow<'static, str> {
        Cow::Borrowed("ES256")
    }

    const fn default_format() -> Cow<'static, str> {
        Cow::Borrowed("jwt")
    }
}

/// Pre-shared key authentication security configuration.
#[skip_serializing_none]
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub struct PskSecurityScheme {
    /// Identifier providing information useful for selection or confirmation.
    pub identity: Option<String>,
}

/// OAuth 2.0 authentication security configuration for systems conformant with
/// [RFC6749](https://www.rfc-editor.org/rfc/rfc6749),
/// [RFC8252](https://www.rfc-editor.org/rfc/rfc8252) and (for the device flow)
/// [RFC8628](https://www.rfc-editor.org/rfc/rfc8628)
#[serde_as]
#[skip_serializing_none]
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub struct OAuth2SecurityScheme {
    /// URI of the authorization server. In the case of the device flow, the URI provided for the
    /// authorization value refers to the device authorization endpoint
    /// ([RFC8628](https://www.rfc-editor.org/rfc/rfc8628)).
    // FIXME: use AnyURI
    pub authorization: Option<String>,

    /// URI of the token server.
    // FIXME: use AnyURI
    pub token: Option<String>,

    /// URI of the refresh server.
    // FIXME: use AnyURI
    pub refresh: Option<String>,

    /// Set of authorization scope identifiers.
    ///
    /// These are provided in tokens returned by an authorization server and associated with forms
    /// in order to identify what resources a client may access and how.
    #[serde(default)]
    #[serde_as(as = "Option<OneOrMany<_>>")]
    pub scopes: Option<Vec<String>>,

    /// Authorization flow.
    pub flow: String,
}

impl OAuth2SecurityScheme {
    /// Creates a new default value with the given `flow`.
    pub fn new(flow: impl Into<String>) -> Self {
        let flow = flow.into();
        Self {
            authorization: Default::default(),
            token: Default::default(),
            refresh: Default::default(),
            scopes: Default::default(),
            flow,
        }
    }
}

/// A link to an arbitrary resource.
#[serde_as]
#[skip_serializing_none]
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Deserialize, Serialize)]
pub struct Link {
    /// Target IRI of a link or submission target of a form.
    pub href: String,

    /// Target attribute providing a hint indicating what the media type
    /// ([RFC2046](https://www.rfc-editor.org/rfc/rfc2046)) of the result of dereferencing the link
    /// should be.
    #[serde(rename = "type")]
    pub ty: Option<String>,

    /// A link relation type identifies the semantics of a link.
    pub rel: Option<String>,

    /// Overrides the link context with the given URI or IRI.
    ///
    /// By default the link context is the Thing itself identified by its `id`.
    // FIXME: use AnyURI
    pub anchor: Option<String>,

    /// One or more sizes for the referenced icon.
    ///
    /// This is only applicable for relation type "icon". The value pattern follows {Height}x{Width} (e.g., "16x16", "16x16 32x32").
    pub sizes: Option<String>,

    /// The language of a linked document.
    #[serde(default)]
    #[serde_as(as = "Option<OneOrMany<_>>")]
    pub hreflang: Option<Vec<LanguageTag<String>>>,
}

/// The representation of an operation over a Thing.
#[serde_as]
#[skip_serializing_none]
#[derive(Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Form<Other: ExtendableThing> {
    /// The semantic intention of performing the operation(s) described by the form.
    #[serde(default, skip_serializing_if = "DefaultedFormOperations::is_default")]
    pub op: DefaultedFormOperations,

    /// Target IRI of a link or submission target of a form.
    // FIXME: use AnyURI
    pub href: String,

    /// A content type.
    ///
    /// It is based on a media type (e.g., text/plain) and potential parameters (e.g.,
    /// charset=utf-8) for the media type ([RFC2046](https://www.rfc-editor.org/rfc/rfc2046)).
    pub content_type: Option<String>,

    /// Content coding values indicate an encoding transformation that has been or can be applied
    /// to a representation.
    ///
    /// Content codings are primarily used to allow a representation to be compressed or otherwise
    /// usefully transformed without losing the identity of its underlying media type and without
    /// loss of information.
    ///
    /// Examples of content coding include "gzip", "deflate", etc. .
    // TODO: check if the subset of possible values is limited by the [IANA HTTP content coding
    // registry](https://www.iana.org/assignments/http-parameters/http-parameters.xhtml#content-coding).
    pub content_coding: Option<String>,

    /// The mechanism by which an interaction will be accomplished for a given protocol when there
    /// are multiple options.
    pub subprotocol: Option<String>,

    /// Set of security definition names, chosen from those defined in
    /// [`security_definitions`](Thing::security_definitions). These must all be satisfied for
    /// access to resources.
    // FIXME: use variant names of KnownSecuritySchemeSubtype + "other" string variant
    #[serde(default)]
    #[serde_as(as = "Option<OneOrMany<_>>")]
    pub security: Option<Vec<String>>,

    /// Set of authorization scope identifiers.
    ///
    /// The values associated with a form should be chosen from those defined in an
    /// [`OAuth2SecurityScheme`] active on that form.
    #[serde(default)]
    #[serde_as(as = "Option<OneOrMany<_>>")]
    pub scopes: Option<Vec<String>>,

    /// The expected response from the call to the resource.
    ///
    /// The response name contains metadata that is only valid for the primary response messages
    pub response: Option<ExpectedResponse<Other::ExpectedResponse>>,

    /// Additional expected responses.
    #[serde(default)]
    #[serde_as(as = "Option<OneOrMany<_>>")]
    pub additional_responses: Option<Vec<AdditionalExpectedResponse>>,

    /// Form extension.
    #[serde(flatten)]
    pub other: Other::Form,
}

impl<Other> Clone for Form<Other>
where
    Other: ExtendableThing,
    Other::ExpectedResponse: Clone,
    Other::Form: Clone,
{
    fn clone(&self) -> Self {
        Self {
            op: self.op.clone(),
            href: self.href.clone(),
            content_type: self.content_type.clone(),
            content_coding: self.content_coding.clone(),
            subprotocol: self.subprotocol.clone(),
            security: self.security.clone(),
            scopes: self.scopes.clone(),
            response: self.response.clone(),
            additional_responses: self.additional_responses.clone(),
            other: self.other.clone(),
        }
    }
}

/// The semantic intention of an operation.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum FormOperation {
    /// Read a property.
    ReadProperty,

    /// Update a property.
    WriteProperty,

    /// Observe a property.
    ///
    /// Identifies an operation to be notified with new data when the property is updated.
    ObserveProperty,

    /// Unobserve a property.
    ///
    /// Stops the notification from a previously observed property.
    UnobserveProperty,

    /// Perform an action.
    InvokeAction,

    /// Get the status of an action.
    QueryAction,

    /// Cancel an ongoing action.
    CancelAction,

    /// Subscribe to an event.
    ///
    /// Identifies an operation to be notified when an event occurs.
    SubscribeEvent,

    /// Unsubscribe from an event.
    ///
    /// Stops the notification from a previously subscribed event.
    UnsubscribeEvent,

    /// Read all the properties in a single interaction.
    ReadAllProperties,

    /// Update all the properties in a single interaction.
    WriteAllProperties,

    /// Read multiple selected properties in a single interaction.
    ReadMultipleProperties,

    /// Update multiple selected properties in a single interaction.
    WriteMultipleProperties,

    /// Observe all the properties in a single interaction.
    ObserveAllProperties,

    /// Unobserve all the properties in a single interaction.
    UnobserveAllProperties,

    /// Subscribe to all events in a single interaction.
    SubscribeAllEvents,

    /// Unsubscribe from all events in a single interaction.
    UnsubscribeAllEvents,

    /// Get the status of all actions in a single interaction.
    QueryAllActions,
}

impl fmt::Display for FormOperation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let s = match self {
            Self::ReadProperty => "readproperty",
            Self::WriteProperty => "writeproperty",
            Self::ObserveProperty => "observeproperty",
            Self::UnobserveProperty => "unobserveproperty",
            Self::InvokeAction => "invokeaction",
            Self::QueryAction => "queryaction",
            Self::CancelAction => "cancelaction",
            Self::SubscribeEvent => "subscribeevent",
            Self::UnsubscribeEvent => "unsubscribeevent",
            Self::ReadAllProperties => "readallproperties",
            Self::WriteAllProperties => "writeallproperties",
            Self::ReadMultipleProperties => "readmultipleproperties",
            Self::WriteMultipleProperties => "writemultipleproperties",
            Self::ObserveAllProperties => "observeallproperties",
            Self::UnobserveAllProperties => "unobserveallproperties",
            Self::SubscribeAllEvents => "subscribeallevents",
            Self::UnsubscribeAllEvents => "unsubscribeallevents",
            Self::QueryAllActions => "queryallactions",
        };

        f.write_str(s)
    }
}

/// A default or custom set of Form operations.
///
/// A `Form` has a different default `op` field depending on its context. With this, it is possible
/// to specify a _default_ operation independently from the context.
///
/// Note: an instance of this enum should not be serialized if it is a `Default` value.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
pub enum DefaultedFormOperations {
    /// The default operation depending on the context.
    #[default]
    Default,

    /// A custom set of operations.
    Custom(Vec<FormOperation>),
}

impl DefaultedFormOperations {
    /// Returns `true` if the operation is a [`Default`](DefaultedFormOperations::Default) value.
    #[inline]
    pub const fn is_default(&self) -> bool {
        matches!(self, Self::Default)
    }
}

impl Serialize for DefaultedFormOperations {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        match self {
            Self::Default => serializer.serialize_none(),
            Self::Custom(ops) if ops.is_empty() => serializer.serialize_none(),
            Self::Custom(ops) => ops.serialize(serializer),
        }
    }
}

impl<'de> Deserialize<'de> for DefaultedFormOperations
where
    OneOrMany<Same>: DeserializeAs<'de, Vec<FormOperation>>,
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let ops = Option::<OneOrMany<_>>::deserialize_as(deserializer)?;
        Ok(ops.map(Self::Custom).unwrap_or(Self::Default))
    }
}

/// The expected response message for the primary response.
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ExpectedResponse<Other> {
    /// A content type.
    ///
    /// It is based on a media type (e.g., text/plain) and potential parameters (e.g.,
    /// charset=utf-8) for the media type ([RFC2046](https://www.rfc-editor.org/rfc/rfc2046)).
    pub content_type: String,

    /// Expected response extension.
    #[serde(flatten)]
    pub other: Other,
}

/// The expected response message for additional responses.
#[skip_serializing_none]
#[derive(Clone, Debug, Default, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct AdditionalExpectedResponse {
    /// It is `true` if an additional response should not be considered an error.
    #[serde(default = "bool_false", skip_serializing_if = "is_false")]
    pub success: bool,

    /// A content type.
    ///
    /// It is based on a media type (e.g., text/plain) and potential parameters (e.g.,
    /// charset=utf-8) for the media type ([RFC2046](https://www.rfc-editor.org/rfc/rfc2046)).
    pub content_type: Option<String>,

    /// The output data schema for an additional response if it differs from the default output data schema.
    ///
    /// It is the name of a previous definition given in the
    /// [`schema_definitions`](Thing::schema_definitions).
    pub schema: Option<String>,
}

const fn bool_false() -> bool {
    false
}

const fn is_false(b: &bool) -> bool {
    !*b
}

#[cfg(test)]
mod test {
    use serde_json::json;
    use time::macros::datetime;

    use crate::hlist::Cons;

    use super::*;

    #[test]
    fn minimal_thing() {
        const RAW: &str = r#"
        {
            "@context": "https://www.w3.org/2022/wot/td/v1.1",
            "id": "urn:dev:ops:32473-WoTLamp-1234",
            "title": "MyLampThing",
            "securityDefinitions": {
                "nosec": {"scheme": "nosec"}
            },
            "security": ["nosec"]
        }"#;

        let expected_thing = Thing {
            context: TD_CONTEXT_11.into(),
            id: Some("urn:dev:ops:32473-WoTLamp-1234".to_string()),
            title: "MyLampThing".to_string(),
            security_definitions: [("nosec".to_string(), SecurityScheme::default())]
                .into_iter()
                .collect(),
            security: vec!["nosec".to_string()],
            ..Default::default()
        };

        let thing: Thing = serde_json::from_str(RAW).unwrap();
        assert_eq!(thing, expected_thing);

        let thing: Thing = serde_json::from_value(serde_json::to_value(thing).unwrap()).unwrap();
        assert_eq!(thing, expected_thing);
    }

    #[test]
    fn complete_thing() {
        const RAW: &str = r#"
        {
          "@context": "https://www.w3.org/2022/wot/td/v1.1",
          "id": "urn:dev:ops:32473-WoTLamp-1234",
          "@type": [
            "Thing",
            "LampThing"
          ],
          "title": "MyLampThing",
          "titles": {
            "en": "MyLampThing",
            "it": "La mia lampada intelligente"
          },
          "description": "A simple smart lamp",
          "descriptions": {
            "en": "A simple smart lamp",
            "it": "Una semplice lampada intelligente"
          },
          "version": {
            "instance": "0.1.0",
            "model": "model"
          },
          "created": "2022-05-01T10:20:42.123Z",
          "modified": "2022-05-10T12:30:00.000+01:00",
          "support": "mailto:mail@test.com",
          "base": "https://mylamp.example.com/",
          "properties": {
            "status": {
              "type": "string",
              "forms": [
                {
                  "href": "https://mylamp.example.com/status"
                }
              ]
            }
          },
          "actions": {
            "toggle": {
              "forms": [
                {
                  "href": "https://mylamp.example.com/toggle"
                }
              ],
              "synchronous": false
            }
          },
          "events": {
            "overheating": {
              "data": {
                "type": "string"
              },
              "forms": [
                {
                  "href": "https://mylamp.example.com/oh",
                  "subprotocol": "longpoll"
                }
              ]
            }
          },
          "links": [
            {
              "href": "https://myswitch.example.com/"
            }
          ],
          "forms": [
            {
              "href": "https://mylamp.example.com/enumerate",
              "op": "readallproperties"
            }
          ],
          "schemaDefinitions": {
              "schema": {
                  "type": "null"
              }
          },
          "securityDefinitions": {
            "nosec": {
              "scheme": "nosec"
            }
          },
          "security": [
            "nosec"
          ],
          "profile": [
              "profile1",
              "profile2"
          ],
          "uriVariables": {
            "uriVariable1": {
              "type": "string"
            },
            "uriVariable2": {
              "type": "number"
            }
          }
        }"#;

        let expected_thing = Thing {
            context: TD_CONTEXT_11.into(),
            id: Some("urn:dev:ops:32473-WoTLamp-1234".to_string()),
            attype: Some(vec!["Thing".to_string(), "LampThing".to_string()]),
            title: "MyLampThing".to_string(),
            titles: Some(
                [
                    ("en".parse().unwrap(), "MyLampThing".to_string()),
                    (
                        "it".parse().unwrap(),
                        "La mia lampada intelligente".to_string(),
                    ),
                ]
                .into_iter()
                .collect(),
            ),
            description: Some("A simple smart lamp".to_string()),
            descriptions: Some(
                [
                    ("en".parse().unwrap(), "A simple smart lamp".to_string()),
                    (
                        "it".parse().unwrap(),
                        "Una semplice lampada intelligente".to_string(),
                    ),
                ]
                .into_iter()
                .collect(),
            ),
            version: Some(VersionInfo {
                instance: "0.1.0".to_string(),
                model: Some("model".to_string()),
            }),
            created: Some(datetime!(2022-05-01 10:20:42.123 UTC)),
            modified: Some(datetime!(2022-05-10 12:30 +1)),
            support: Some("mailto:mail@test.com".to_string()),
            base: Some("https://mylamp.example.com/".to_string()),
            properties: Some(
                [(
                    "status".to_string(),
                    PropertyAffordance {
                        interaction: InteractionAffordance {
                            forms: vec![Form {
                                href: "https://mylamp.example.com/status".to_string(),
                                ..Form::default()
                            }],
                            ..Default::default()
                        },
                        data_schema: DataSchema {
                            subtype: Some(DataSchemaSubtype::String(Default::default())),
                            ..Default::default()
                        },
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
            ),
            actions: Some(
                [(
                    "toggle".to_string(),
                    ActionAffordance {
                        interaction: InteractionAffordance {
                            forms: vec![Form {
                                href: "https://mylamp.example.com/toggle".to_string(),
                                ..Default::default()
                            }],
                            ..Default::default()
                        },
                        synchronous: Some(false),
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
            ),
            events: Some(
                [(
                    "overheating".to_string(),
                    EventAffordance {
                        interaction: InteractionAffordance {
                            forms: vec![Form {
                                href: "https://mylamp.example.com/oh".to_string(),
                                subprotocol: Some("longpoll".to_string()),
                                ..Default::default()
                            }],
                            ..Default::default()
                        },
                        data: Some(DataSchema {
                            subtype: Some(DataSchemaSubtype::String(StringSchema::default())),
                            ..Default::default()
                        }),
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
            ),
            links: Some(vec![Link {
                href: "https://myswitch.example.com/".to_string(),
                ..Default::default()
            }]),
            forms: Some(vec![Form {
                op: DefaultedFormOperations::Custom(vec![FormOperation::ReadAllProperties]),
                href: "https://mylamp.example.com/enumerate".to_string(),
                ..Default::default()
            }]),
            schema_definitions: Some(
                [(
                    "schema".to_string(),
                    DataSchema {
                        subtype: Some(DataSchemaSubtype::Null),
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
            ),
            security_definitions: [("nosec".to_string(), SecurityScheme::default())]
                .into_iter()
                .collect(),
            security: vec!["nosec".to_string()],
            profile: Some(vec!["profile1".to_string(), "profile2".to_string()]),
            uri_variables: Some(
                [
                    (
                        "uriVariable1".to_string(),
                        DataSchema {
                            subtype: Some(DataSchemaSubtype::String(Default::default())),
                            ..Default::default()
                        },
                    ),
                    (
                        "uriVariable2".to_string(),
                        DataSchema {
                            subtype: Some(DataSchemaSubtype::Number(Default::default())),
                            ..Default::default()
                        },
                    ),
                ]
                .into_iter()
                .collect(),
            ),
            ..Default::default()
        };

        let thing: Thing = serde_json::from_str(RAW).unwrap();
        assert_eq!(thing, expected_thing);

        let thing: Thing = serde_json::from_value(serde_json::to_value(thing).unwrap()).unwrap();
        assert_eq!(thing, expected_thing);
    }

    #[test]
    fn default_context() {
        const RAW: &str = r#"
        {
          "title": "MyLampThing",
          "securityDefinitions": {
            "nosec": {
              "scheme": "nosec"
            }
          },
          "security": [
            "nosec"
          ]
        }"#;

        let expected_thing = Thing {
            context: TD_CONTEXT_11.into(),
            title: "MyLampThing".to_string(),
            security_definitions: [("nosec".to_string(), SecurityScheme::default())]
                .into_iter()
                .collect(),
            security: vec!["nosec".to_string()],
            ..Default::default()
        };

        let thing: Thing = serde_json::from_str(RAW).unwrap();
        assert_eq!(thing, expected_thing);
    }

    #[derive(Serialize, Deserialize)]
    struct A(i32);

    impl Default for A {
        fn default() -> Self {
            A(42)
        }
    }

    #[derive(Default, Serialize, Deserialize)]
    struct ThingExtA {
        a: A,
    }

    #[derive(Default, Serialize, Deserialize)]
    struct IntAffExtA {
        b: A,
    }

    #[derive(Default, Serialize, Deserialize)]
    struct ActionAffExtA {
        c: A,
    }

    #[derive(Default, Serialize, Deserialize)]
    struct PropAffExtA {
        d: A,
    }

    #[derive(Default, Serialize, Deserialize)]
    struct EventAffExtA {
        e: A,
    }

    #[derive(Default, Serialize, Deserialize)]
    struct FormExtA {
        f: A,
    }

    #[derive(Default, Serialize, Deserialize)]
    struct RespExtA {
        g: A,
    }

    #[derive(Default, Serialize, Deserialize)]
    struct DataSchemaExtA {
        h: A,
    }

    #[derive(Default, Serialize, Deserialize)]
    struct ObjectSchemaExtA {
        i: A,
    }

    #[derive(Default, Serialize, Deserialize)]
    struct ArraySchemaExtA {
        j: A,
    }

    impl ExtendableThing for ThingExtA {
        type InteractionAffordance = IntAffExtA;
        type PropertyAffordance = PropAffExtA;
        type ActionAffordance = ActionAffExtA;
        type EventAffordance = EventAffExtA;
        type Form = FormExtA;
        type ExpectedResponse = RespExtA;
        type DataSchema = DataSchemaExtA;
        type ObjectSchema = ObjectSchemaExtA;
        type ArraySchema = ArraySchemaExtA;
    }

    #[test]
    fn extend_single_thing() {
        let thing = Thing::<ThingExtA> {
            context: "test".into(),
            properties: Some(
                [(
                    "prop".to_string(),
                    PropertyAffordance {
                        interaction: InteractionAffordance {
                            other: IntAffExtA { b: A(1) },
                            ..Default::default()
                        },
                        data_schema: DataSchema {
                            subtype: Some(DataSchemaSubtype::Array(ArraySchema {
                                other: ArraySchemaExtA { j: A(2) },
                                ..Default::default()
                            })),
                            other: DataSchemaExtA { h: A(3) },
                            ..Default::default()
                        },
                        other: PropAffExtA { d: A(4) },
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
            ),
            actions: Some(
                [(
                    "action".to_string(),
                    ActionAffordance {
                        interaction: InteractionAffordance {
                            other: IntAffExtA { b: A(5) },
                            ..Default::default()
                        },
                        input: Some(DataSchema {
                            subtype: Some(DataSchemaSubtype::Object(ObjectSchema {
                                other: ObjectSchemaExtA { i: A(6) },
                                ..Default::default()
                            })),
                            other: DataSchemaExtA { h: A(7) },
                            ..Default::default()
                        }),
                        output: Some(DataSchema::default()),
                        other: ActionAffExtA { c: A(8) },
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
            ),
            events: Some(
                [(
                    "event".to_string(),
                    EventAffordance {
                        other: EventAffExtA { e: A(9) },
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
            ),
            forms: Some(vec![Form {
                response: Some(ExpectedResponse {
                    other: RespExtA { g: A(10) },
                    ..Default::default()
                }),
                other: FormExtA { f: A(11) },
                ..Default::default()
            }]),
            schema_definitions: Some(
                [(
                    "schema".to_string(),
                    DataSchema {
                        subtype: Some(DataSchemaSubtype::Null),
                        other: DataSchemaExtA { h: A(12) },
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
            ),
            other: ThingExtA { a: A(13) },
            ..Default::default()
        };

        let thing_json = serde_json::to_value(thing).unwrap();
        assert_eq!(
            thing_json,
            json![{
                "@context": "test",
                "title": "",
                "properties": {
                    "prop": {
                        "b": 1,
                        "j": 2,
                        "h": 3,
                        "d": 4,
                        "forms": [],
                        "type": "array",
                        "readOnly": false,
                        "writeOnly": false,
                    }
                },
                "actions": {
                    "action": {
                        "b": 5,
                        "input": {
                            "i": 6,
                            "h": 7,
                            "readOnly": false,
                            "writeOnly": false,
                            "type": "object",
                        },
                        "output": {
                            "h": 42,
                            "readOnly": false,
                            "writeOnly": false,
                        },
                        "forms": [],
                        "idempotent": false,
                        "safe": false,
                        "c": 8,
                    }
                },
                "events": {
                    "event": {
                        "b": 42,
                        "e": 9,
                        "forms": [],
                    }
                },
                "forms": [{
                    "href": "",
                    "response": {
                        "contentType": "",
                        "g": 10,
                    },
                    "f": 11,
                }],
                "schemaDefinitions": {
                    "schema": {
                        "type": "null",
                        "readOnly": false,
                        "writeOnly": false,
                        "h": 12,
                    }
                },
                "security": [],
                "securityDefinitions": {},
                "a": 13,
            }],
        );
    }

    #[test]
    fn extend_single_thing_with_hlist() {
        let thing = Thing::<Cons<ThingExtA, Nil>> {
            context: "test".into(),
            properties: Some(
                [(
                    "prop".to_string(),
                    PropertyAffordance {
                        interaction: InteractionAffordance {
                            other: Nil::cons(IntAffExtA { b: A(1) }),
                            ..Default::default()
                        },
                        data_schema: DataSchema {
                            subtype: Some(DataSchemaSubtype::Array(ArraySchema {
                                other: Nil::cons(ArraySchemaExtA { j: A(2) }),
                                ..Default::default()
                            })),
                            other: Nil::cons(DataSchemaExtA { h: A(3) }),
                            ..Default::default()
                        },
                        other: Nil::cons(PropAffExtA { d: A(4) }),
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
            ),
            actions: Some(
                [(
                    "action".to_string(),
                    ActionAffordance {
                        interaction: InteractionAffordance {
                            other: Nil::cons(IntAffExtA { b: A(5) }),
                            ..Default::default()
                        },
                        input: Some(DataSchema {
                            subtype: Some(DataSchemaSubtype::Object(ObjectSchema {
                                other: Nil::cons(ObjectSchemaExtA { i: A(6) }),
                                ..Default::default()
                            })),
                            other: Nil::cons(DataSchemaExtA { h: A(7) }),
                            ..Default::default()
                        }),
                        output: Some(DataSchema::default()),
                        other: Nil::cons(ActionAffExtA { c: A(8) }),
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
            ),
            events: Some(
                [(
                    "event".to_string(),
                    EventAffordance {
                        other: Nil::cons(EventAffExtA { e: A(9) }),
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
            ),
            forms: Some(vec![Form {
                response: Some(ExpectedResponse {
                    other: Nil::cons(RespExtA { g: A(10) }),
                    ..Default::default()
                }),
                other: Nil::cons(FormExtA { f: A(11) }),
                ..Default::default()
            }]),
            other: Nil::cons(ThingExtA { a: A(12) }),
            ..Default::default()
        };

        let thing_json = serde_json::to_value(thing).unwrap();
        assert_eq!(
            thing_json,
            json!({
                "@context": "test",
                "title": "",
                "properties": {
                    "prop": {
                        "b": 1,
                        "j": 2,
                        "h": 3,
                        "d": 4,
                        "forms": [],
                        "type": "array",
                        "readOnly": false,
                        "writeOnly": false,
                    }
                },
                "actions": {
                    "action": {
                        "b": 5,
                        "input": {
                            "i": 6,
                            "h": 7,
                            "readOnly": false,
                            "writeOnly": false,
                            "type": "object",
                        },
                        "output": {
                            "h": 42,
                            "readOnly": false,
                            "writeOnly": false,
                        },
                        "forms": [],
                        "idempotent": false,
                        "safe": false,
                        "c": 8,
                    }
                },
                "events": {
                    "event": {
                        "b": 42,
                        "e": 9,
                        "forms": [],
                    }
                },
                "forms": [{
                    "href": "",
                    "response": {
                        "contentType": "",
                        "g": 10,
                    },
                    "f": 11,
                }],
                "security": [],
                "securityDefinitions": {},
                "a": 12,
            }),
        );
    }

    #[derive(Default, Serialize, Deserialize)]
    struct ThingExtB {
        k: A,
    }

    #[derive(Default, Serialize, Deserialize)]
    struct IntAffExtB {
        l: A,
    }

    #[derive(Default, Serialize, Deserialize)]
    struct ActionAffExtB {
        m: A,
    }

    #[derive(Default, Serialize, Deserialize)]
    struct PropAffExtB {
        n: A,
    }

    #[derive(Default, Serialize, Deserialize)]
    struct EventAffExtB {
        o: A,
    }

    #[derive(Default, Serialize, Deserialize)]
    struct FormExtB {
        p: A,
    }

    #[derive(Default, Serialize, Deserialize)]
    struct RespExtB {
        q: A,
    }

    #[derive(Default, Serialize, Deserialize)]
    struct DataSchemaExtB {
        r: A,
    }

    #[derive(Default, Serialize, Deserialize)]
    struct ObjectSchemaExtB {
        s: A,
    }

    #[derive(Default, Serialize, Deserialize)]
    struct ArraySchemaExtB {
        t: A,
    }

    impl ExtendableThing for ThingExtB {
        type InteractionAffordance = IntAffExtB;
        type PropertyAffordance = PropAffExtB;
        type ActionAffordance = ActionAffExtB;
        type EventAffordance = EventAffExtB;
        type Form = FormExtB;
        type ExpectedResponse = RespExtB;
        type DataSchema = DataSchemaExtB;
        type ObjectSchema = ObjectSchemaExtB;
        type ArraySchema = ArraySchemaExtB;
    }

    #[test]
    fn extend_thing_with_two() {
        let thing = Thing::<Cons<ThingExtB, Cons<ThingExtA, Nil>>> {
            context: "test".into(),
            properties: Some(
                [(
                    "prop".to_string(),
                    PropertyAffordance {
                        interaction: InteractionAffordance {
                            other: Nil::cons(IntAffExtA { b: A(1) }).cons(IntAffExtB { l: A(2) }),
                            ..Default::default()
                        },
                        data_schema: DataSchema {
                            subtype: Some(DataSchemaSubtype::Array(ArraySchema {
                                other: Nil::cons(ArraySchemaExtA { j: A(3) })
                                    .cons(ArraySchemaExtB { t: A(4) }),
                                ..Default::default()
                            })),
                            other: Nil::cons(DataSchemaExtA { h: A(5) })
                                .cons(DataSchemaExtB { r: A(6) }),
                            ..Default::default()
                        },
                        other: Nil::cons(PropAffExtA { d: A(7) }).cons(PropAffExtB { n: A(8) }),
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
            ),
            actions: Some(
                [(
                    "action".to_string(),
                    ActionAffordance {
                        interaction: InteractionAffordance {
                            other: Nil::cons(IntAffExtA { b: A(9) }).cons(IntAffExtB { l: A(10) }),
                            ..Default::default()
                        },
                        input: Some(DataSchema {
                            subtype: Some(DataSchemaSubtype::Object(ObjectSchema {
                                other: Nil::cons(ObjectSchemaExtA { i: A(11) })
                                    .cons(ObjectSchemaExtB { s: A(12) }),
                                ..Default::default()
                            })),
                            other: Nil::cons(DataSchemaExtA { h: A(13) })
                                .cons(DataSchemaExtB { r: A(14) }),
                            ..Default::default()
                        }),
                        output: Some(DataSchema::default()),
                        other: Nil::cons(ActionAffExtA { c: A(15) })
                            .cons(ActionAffExtB { m: A(16) }),
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
            ),
            events: Some(
                [(
                    "event".to_string(),
                    EventAffordance {
                        other: Nil::cons(EventAffExtA { e: A(17) }).cons(EventAffExtB { o: A(18) }),
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
            ),
            forms: Some(vec![Form {
                response: Some(ExpectedResponse {
                    other: Nil::cons(RespExtA { g: A(19) }).cons(RespExtB { q: A(20) }),
                    ..Default::default()
                }),
                other: Nil::cons(FormExtA { f: A(21) }).cons(FormExtB { p: A(22) }),
                ..Default::default()
            }]),
            other: Nil::cons(ThingExtA { a: A(23) }).cons(ThingExtB { k: A(24) }),
            ..Default::default()
        };

        let thing_json = serde_json::to_value(thing).unwrap();
        assert_eq!(
            thing_json,
            json!({
                "@context": "test",
                "title": "",
                "properties": {
                    "prop": {
                        "b": 1,
                        "l": 2,
                        "j": 3,
                        "t": 4,
                        "h": 5,
                        "r": 6,
                        "d": 7,
                        "n": 8,
                        "forms": [],
                        "type": "array",
                        "readOnly": false,
                        "writeOnly": false,
                    }
                },
                "actions": {
                    "action": {
                        "b": 9,
                        "l": 10,
                        "input": {
                            "i": 11,
                            "s": 12,
                            "h": 13,
                            "r": 14,
                            "readOnly": false,
                            "writeOnly": false,
                            "type": "object",
                        },
                        "output": {
                            "h": 42,
                            "r": 42,
                            "readOnly": false,
                            "writeOnly": false,
                        },
                        "forms": [],
                        "idempotent": false,
                        "safe": false,
                        "c": 15,
                        "m": 16,
                    }
                },
                "events": {
                    "event": {
                        "b": 42,
                        "l": 42,
                        "e": 17,
                        "o": 18,
                        "forms": [],
                    }
                },
                "forms": [{
                    "href": "",
                    "response": {
                        "contentType": "",
                        "g": 19,
                        "q": 20,
                    },
                    "f": 21,
                    "p": 22,
                }],
                "security": [],
                "securityDefinitions": {},
                "a": 23,
                "k": 24,
            }),
        );
    }

    #[test]
    fn dummy_http() {
        #[derive(Serialize, Deserialize, Default)]
        struct HttpThing {}

        #[derive(Deserialize, Serialize)]
        #[serde(rename_all = "SCREAMING_SNAKE_CASE")]
        enum HttpMethod {
            Get,
            Put,
            Post,
            Delete,
            Patch,
        }

        #[derive(Deserialize, Serialize)]
        struct HttpMessageHeader {
            #[serde(rename = "htv:fieldName")]
            field_name: Option<String>,
            #[serde(rename = "htv:fieldValue")]
            field_value: Option<String>,
        }

        #[derive(Deserialize, Serialize, Default)]
        struct HttpResponse {
            #[serde(rename = "htv:headers")]
            headers: Vec<HttpMessageHeader>,
            #[serde(rename = "htv:statusCodeValue")]
            status_code_value: Option<usize>,
        }

        #[derive(Default, Deserialize, Serialize)]
        struct HttpForm {
            #[serde(rename = "htv:methodName")]
            method_name: Option<HttpMethod>,
        }

        impl ExtendableThing for HttpThing {
            type InteractionAffordance = ();
            type PropertyAffordance = ();
            type ActionAffordance = ();
            type EventAffordance = ();
            type Form = HttpForm;
            type ExpectedResponse = HttpResponse;
            type DataSchema = ();
            type ObjectSchema = ();
            type ArraySchema = ();
        }

        let thing = Thing::<Cons<ThingExtB, Cons<HttpThing, Cons<ThingExtA, Nil>>>> {
            context: "test".into(),
            properties: Some(
                [(
                    "prop".to_string(),
                    PropertyAffordance {
                        interaction: InteractionAffordance {
                            other: Nil::cons(IntAffExtA { b: A(1) })
                                .cons(())
                                .cons(IntAffExtB { l: A(2) }),
                            ..Default::default()
                        },
                        data_schema: DataSchema {
                            subtype: Some(DataSchemaSubtype::Array(ArraySchema {
                                other: Nil::cons(ArraySchemaExtA { j: A(3) })
                                    .cons(())
                                    .cons(ArraySchemaExtB { t: A(4) }),
                                ..Default::default()
                            })),
                            other: Nil::cons(DataSchemaExtA { h: A(5) })
                                .cons(())
                                .cons(DataSchemaExtB { r: A(6) }),
                            ..Default::default()
                        },
                        other: Nil::cons(PropAffExtA { d: A(7) })
                            .cons(())
                            .cons(PropAffExtB { n: A(8) }),
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
            ),
            actions: Some(
                [(
                    "action".to_string(),
                    ActionAffordance {
                        interaction: InteractionAffordance {
                            forms: vec![Form {
                                other: Nil::cons(FormExtA::default())
                                    .cons(HttpForm {
                                        method_name: Some(HttpMethod::Put),
                                    })
                                    .cons(FormExtB::default()),
                                ..Default::default()
                            }],
                            other: Nil::cons(IntAffExtA { b: A(9) })
                                .cons(())
                                .cons(IntAffExtB { l: A(10) }),
                            ..Default::default()
                        },
                        input: Some(DataSchema {
                            subtype: Some(DataSchemaSubtype::Object(ObjectSchema {
                                other: Nil::cons(ObjectSchemaExtA { i: A(11) })
                                    .cons(())
                                    .cons(ObjectSchemaExtB { s: A(12) }),
                                ..Default::default()
                            })),
                            other: Nil::cons(DataSchemaExtA { h: A(13) })
                                .cons(())
                                .cons(DataSchemaExtB { r: A(14) }),
                            ..Default::default()
                        }),
                        output: Some(DataSchema::default()),
                        other: Nil::cons(ActionAffExtA { c: A(15) })
                            .cons(())
                            .cons(ActionAffExtB { m: A(16) }),
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
            ),
            events: Some(
                [(
                    "event".to_string(),
                    EventAffordance {
                        other: Nil::cons(EventAffExtA { e: A(17) })
                            .cons(())
                            .cons(EventAffExtB { o: A(18) }),
                        ..Default::default()
                    },
                )]
                .into_iter()
                .collect(),
            ),
            forms: Some(vec![Form {
                response: Some(ExpectedResponse {
                    other: Nil::cons(RespExtA { g: A(19) })
                        .cons(HttpResponse {
                            headers: vec![HttpMessageHeader {
                                field_name: Some("hello".to_string()),
                                field_value: Some("world".to_string()),
                            }],
                            status_code_value: Some(200),
                        })
                        .cons(RespExtB { q: A(20) }),
                    ..Default::default()
                }),
                other: Nil::cons(FormExtA { f: A(21) })
                    .cons(HttpForm {
                        method_name: Some(HttpMethod::Get),
                    })
                    .cons(FormExtB { p: A(22) }),
                ..Default::default()
            }]),
            other: Nil::cons(ThingExtA { a: A(23) })
                .cons(HttpThing {})
                .cons(ThingExtB { k: A(24) }),
            ..Default::default()
        };

        let thing_json = serde_json::to_value(thing).unwrap();
        assert_eq!(
            thing_json,
            json!({
                "@context": "test",
                "title": "",
                "properties": {
                    "prop": {
                        "b": 1,
                        "l": 2,
                        "j": 3,
                        "t": 4,
                        "h": 5,
                        "r": 6,
                        "d": 7,
                        "n": 8,
                        "forms": [],
                        "type": "array",
                        "readOnly": false,
                        "writeOnly": false,
                    }
                },
                "actions": {
                    "action": {
                        "b": 9,
                        "l": 10,
                        "input": {
                            "i": 11,
                            "s": 12,
                            "h": 13,
                            "r": 14,
                            "readOnly": false,
                            "writeOnly": false,
                            "type": "object",
                        },
                        "output": {
                            "h": 42,
                            "r": 42,
                            "readOnly": false,
                            "writeOnly": false,
                        },
                        "forms": [
                            {
                                "f": 42,
                                "href": "",
                                "htv:methodName": "PUT",
                                "p": 42,
                            }
                        ],
                        "idempotent": false,
                        "safe": false,
                        "c": 15,
                        "m": 16,
                    }
                },
                "events": {
                    "event": {
                        "b": 42,
                        "l": 42,
                        "e": 17,
                        "o": 18,
                        "forms": [],
                    }
                },
                "forms": [{
                    "href": "",
                    "response": {
                        "contentType": "",
                        "g": 19,
                        "q": 20,
                        "htv:headers": [{
                            "htv:fieldName": "hello",
                            "htv:fieldValue": "world",
                        }],
                        "htv:statusCodeValue": 200,
                    },
                    "f": 21,
                    "p": 22,
                    "htv:methodName": "GET",
                }],
                "security": [],
                "securityDefinitions": {},
                "a": 23,
                "k": 24,
            }),
        );
    }

    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    struct DataSchemaExt {}

    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    struct ArraySchemaExt {}

    #[derive(Debug, PartialEq, Serialize, Deserialize)]
    struct ObjectSchemaExt {}

    #[test]
    fn default_array_schema() {
        ArraySchema::<DataSchemaExt, (), ObjectSchemaExt>::default();
    }

    #[test]
    fn default_object_schema() {
        ObjectSchema::<DataSchemaExt, ArraySchemaExt, ()>::default();
    }

    #[test]
    fn serde_empty_additional_expected_response() {
        let response: AdditionalExpectedResponse = serde_json::from_value(json!({})).unwrap();
        assert_eq!(
            response,
            AdditionalExpectedResponse {
                success: false,
                content_type: None,
                schema: None,
            },
        );

        assert_eq!(serde_json::to_value(response).unwrap(), json!({}));
    }

    #[test]
    fn serde_full_additional_expected_response() {
        let raw_data = json!({
            "success": true,
            "contentType": "application/json",
            "schema": "test",
        });

        let response: AdditionalExpectedResponse =
            serde_json::from_value(raw_data.clone()).unwrap();

        assert_eq!(
            response,
            AdditionalExpectedResponse {
                success: true,
                content_type: Some("application/json".to_string()),
                schema: Some("test".to_string()),
            },
        );

        assert_eq!(serde_json::to_value(response).unwrap(), raw_data);
    }

    #[test]
    fn combo_security_scheme() {
        let raw_data = json!({
            "oneOf": "simple",
        });
        let combo: ComboSecurityScheme = serde_json::from_value(raw_data.clone()).unwrap();
        assert_eq!(
            combo,
            ComboSecurityScheme::OneOf(vec!["simple".to_string()]),
        );
        assert_eq!(serde_json::to_value(combo).unwrap(), raw_data);

        let raw_data = json!({
            "oneOf": ["data1", "data2"],
        });
        let combo: ComboSecurityScheme = serde_json::from_value(raw_data.clone()).unwrap();
        assert_eq!(
            combo,
            ComboSecurityScheme::OneOf(vec!["data1".to_string(), "data2".to_string()]),
        );
        assert_eq!(serde_json::to_value(combo).unwrap(), raw_data);

        let raw_data = json!({
            "allOf": "simple",
        });
        let combo: ComboSecurityScheme = serde_json::from_value(raw_data.clone()).unwrap();
        assert_eq!(
            combo,
            ComboSecurityScheme::AllOf(vec!["simple".to_string()]),
        );
        assert_eq!(serde_json::to_value(combo).unwrap(), raw_data);

        let raw_data = json!({
            "allOf": ["data1", "data2"],
        });
        let combo: ComboSecurityScheme = serde_json::from_value(raw_data.clone()).unwrap();
        assert_eq!(
            combo,
            ComboSecurityScheme::AllOf(vec!["data1".to_string(), "data2".to_string()]),
        );
        assert_eq!(serde_json::to_value(combo).unwrap(), raw_data);
    }

    #[test]
    fn minimum_partial_ord_trivial() {
        assert_eq!(
            Minimum::Inclusive(5).partial_cmp(&Minimum::Inclusive(5)),
            Some(Ordering::Equal),
        );
        assert_eq!(
            Minimum::Inclusive(5).partial_cmp(&Minimum::Inclusive(6)),
            Some(Ordering::Less),
        );
        assert_eq!(
            Minimum::Inclusive(6).partial_cmp(&Minimum::Inclusive(5)),
            Some(Ordering::Greater),
        );

        assert_eq!(
            Minimum::Exclusive(5).partial_cmp(&Minimum::Exclusive(5)),
            Some(Ordering::Equal),
        );
        assert_eq!(
            Minimum::Exclusive(5).partial_cmp(&Minimum::Exclusive(6)),
            Some(Ordering::Less),
        );
        assert_eq!(
            Minimum::Exclusive(6).partial_cmp(&Minimum::Exclusive(5)),
            Some(Ordering::Greater),
        );
    }

    #[test]
    fn minimum_partial_ord_complex() {
        assert_eq!(
            Minimum::Inclusive(4).partial_cmp(&Minimum::Exclusive(5)),
            Some(Ordering::Less),
        );

        assert_eq!(
            Minimum::Inclusive(5).partial_cmp(&Minimum::Exclusive(5)),
            Some(Ordering::Less),
        );

        assert_eq!(
            Minimum::Inclusive(6).partial_cmp(&Minimum::Exclusive(5)),
            None,
        );

        assert_eq!(
            Minimum::Exclusive(4).partial_cmp(&Minimum::Inclusive(5)),
            None,
        );

        assert_eq!(
            Minimum::Exclusive(5).partial_cmp(&Minimum::Inclusive(5)),
            Some(Ordering::Greater),
        );

        assert_eq!(
            Minimum::Exclusive(6).partial_cmp(&Minimum::Inclusive(5)),
            Some(Ordering::Greater),
        );
    }

    #[test]
    fn maximum_partial_ord_trivial() {
        use std::cmp::Ordering;
        assert_eq!(
            Maximum::Inclusive(5).partial_cmp(&Maximum::Inclusive(5)),
            Some(Ordering::Equal),
        );
        assert_eq!(
            Maximum::Inclusive(5).partial_cmp(&Maximum::Inclusive(6)),
            Some(Ordering::Less),
        );
        assert_eq!(
            Maximum::Inclusive(6).partial_cmp(&Maximum::Inclusive(5)),
            Some(Ordering::Greater),
        );

        assert_eq!(
            Maximum::Exclusive(5).partial_cmp(&Maximum::Exclusive(5)),
            Some(Ordering::Equal),
        );
        assert_eq!(
            Maximum::Exclusive(5).partial_cmp(&Maximum::Exclusive(6)),
            Some(Ordering::Less),
        );
        assert_eq!(
            Maximum::Exclusive(6).partial_cmp(&Maximum::Exclusive(5)),
            Some(Ordering::Greater),
        );
    }

    #[test]
    fn maximum_partial_ord_complex() {
        assert_eq!(
            Maximum::Inclusive(4).partial_cmp(&Maximum::Exclusive(5)),
            None,
        );

        assert_eq!(
            Maximum::Inclusive(5).partial_cmp(&Maximum::Exclusive(5)),
            Some(Ordering::Greater),
        );

        assert_eq!(
            Maximum::Inclusive(6).partial_cmp(&Maximum::Exclusive(5)),
            Some(Ordering::Greater),
        );

        assert_eq!(
            Maximum::Exclusive(4).partial_cmp(&Maximum::Inclusive(5)),
            Some(Ordering::Less)
        );

        assert_eq!(
            Maximum::Exclusive(5).partial_cmp(&Maximum::Inclusive(5)),
            Some(Ordering::Less),
        );

        assert_eq!(
            Maximum::Exclusive(6).partial_cmp(&Maximum::Inclusive(5)),
            None
        );
    }

    #[test]
    fn minimum_maximum_mixed_partial_ord_trivial() {
        assert_eq!(
            Minimum::Inclusive(4).partial_cmp(&Maximum::Inclusive(5)),
            Some(Ordering::Less),
        );
        assert_eq!(
            Minimum::Inclusive(5).partial_cmp(&Maximum::Inclusive(5)),
            Some(Ordering::Equal),
        );
        assert_eq!(
            Minimum::Inclusive(6).partial_cmp(&Maximum::Inclusive(5)),
            Some(Ordering::Greater),
        );

        assert_eq!(
            Maximum::Inclusive(4).partial_cmp(&Minimum::Inclusive(5)),
            Some(Ordering::Less),
        );
        assert_eq!(
            Maximum::Inclusive(5).partial_cmp(&Minimum::Inclusive(5)),
            Some(Ordering::Equal),
        );
        assert_eq!(
            Maximum::Inclusive(6).partial_cmp(&Minimum::Inclusive(5)),
            Some(Ordering::Greater),
        );
    }

    #[test]
    fn minimum_maximum_mixed_partial_ord_complex() {
        assert_eq!(
            Minimum::Inclusive(4).partial_cmp(&Maximum::Exclusive(5)),
            None,
        );
        assert_eq!(
            Minimum::Inclusive(5).partial_cmp(&Maximum::Exclusive(5)),
            Some(Ordering::Greater)
        );
        assert_eq!(
            Minimum::Inclusive(6).partial_cmp(&Maximum::Exclusive(5)),
            Some(Ordering::Greater)
        );

        assert_eq!(
            Minimum::Exclusive(4).partial_cmp(&Maximum::Inclusive(5)),
            None,
        );
        assert_eq!(
            Minimum::Exclusive(5).partial_cmp(&Maximum::Inclusive(5)),
            Some(Ordering::Greater),
        );
        assert_eq!(
            Minimum::Exclusive(6).partial_cmp(&Maximum::Inclusive(5)),
            Some(Ordering::Greater),
        );

        assert_eq!(
            Maximum::Inclusive(4).partial_cmp(&Minimum::Exclusive(5)),
            Some(Ordering::Less),
        );
        assert_eq!(
            Maximum::Inclusive(5).partial_cmp(&Minimum::Exclusive(5)),
            Some(Ordering::Less),
        );
        assert_eq!(
            Maximum::Inclusive(6).partial_cmp(&Minimum::Exclusive(5)),
            None,
        );

        assert_eq!(
            Maximum::Exclusive(4).partial_cmp(&Minimum::Inclusive(5)),
            Some(Ordering::Less),
        );
        assert_eq!(
            Maximum::Exclusive(5).partial_cmp(&Minimum::Inclusive(5)),
            Some(Ordering::Less),
        );
        assert_eq!(
            Maximum::Exclusive(6).partial_cmp(&Minimum::Inclusive(5)),
            None,
        );
    }

    #[test]
    fn serde_number_schema() {
        let data: NumberSchema = serde_json::from_value(json! {
            {
                "minimum": 0.5,
                "maximum": 1.,
                "multipleOf": 0.5,
            }
        })
        .unwrap();

        assert_eq!(
            data,
            NumberSchema {
                minimum: Some(Minimum::Inclusive(0.5)),
                maximum: Some(Maximum::Inclusive(1.)),
                multiple_of: Some(0.5),
            },
        );

        let data: NumberSchema = serde_json::from_value(json! {
            {
                "exclusiveMinimum": 0.5,
                "exclusiveMaximum": 1.,
                "multipleOf": 0.5,
            }
        })
        .unwrap();

        assert_eq!(
            data,
            NumberSchema {
                minimum: Some(Minimum::Exclusive(0.5)),
                maximum: Some(Maximum::Exclusive(1.)),
                multiple_of: Some(0.5),
            },
        );
    }

    #[test]
    fn serde_integer_schema() {
        let data: IntegerSchema = serde_json::from_value(json! {
            {
                "minimum": 5,
                "maximum": 10,
                "multipleOf": 2,
            }
        })
        .unwrap();

        assert_eq!(
            data,
            IntegerSchema {
                minimum: Some(Minimum::Inclusive(5)),
                maximum: Some(Maximum::Inclusive(10)),
                multiple_of: Some(2),
            },
        );

        let data: IntegerSchema = serde_json::from_value(json! {
            {
                "exclusiveMinimum": 5,
                "exclusiveMaximum": 10,
            }
        })
        .unwrap();

        assert_eq!(
            data,
            IntegerSchema {
                minimum: Some(Minimum::Exclusive(5)),
                maximum: Some(Maximum::Exclusive(10)),
                multiple_of: None,
            },
        );
    }

    #[test]
    fn form_almost_default_serialization() {
        let form: Form<Nil> = Form {
            href: "href".to_string(),
            ..Default::default()
        };

        let form_json = serde_json::to_value(form).unwrap();
        assert_eq!(
            form_json,
            json!({
                "href": "href",
            }),
        )
    }
}