gis-tools 1.13.1

A collection of geospatial tools primarily designed for WGS84, Web Mercator, and S2.
Documentation
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
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
// https://docs.ogc.org/is/18-010r7/18-010r7.html
use crate::proj::{
    AxisSwapConverter, CoordinateStep, Proj, ProjectionTransform, Step, derive_sphere,
    name_to_unit, to_camel_case,
};
use alloc::{
    boxed::Box,
    format,
    rc::Rc,
    string::{String, ToString},
    vec,
    vec::Vec,
};
use core::cell::RefCell;
use libm::fabs;
use serde::{Deserialize, Serialize};

// NOTE: Because the 0.7 spec is not always being followed correctly by generators, serde(default) is applied to everything

/// Helper functions that default to do nothing
pub trait ToProjJSON {
    /// Set Usage
    fn set_usage(&mut self, _usage: ObjectUsage) {}
    /// Set an Anchor
    fn set_anchor(&mut self, _anchor: String) {}
    /// Set a Unit
    fn set_unit(&mut self, _unit: Unit) {}
    /// Set an Id
    fn set_id(&mut self, _id: Id) {}
    /// Set an Axis
    fn set_axis(&mut self, _axis: Axis) {}
    /// Set a CoordinateSystem
    fn set_coordinate_system(&mut self, _cs: CoordinateSystem) {}
    /// Set Temporal Extent
    fn set_temporal_extent(&mut self, _extent: TemporalExtent) {}
    /// Set Vertical Extent
    fn set_vertical_extent(&mut self, _extent: VerticalExtent) {}
    /// Set Bounding Box
    fn set_bbox(&mut self, _bbox: ProjBBox) {}
    /// Set Area
    fn set_area(&mut self, _area: Option<String>) {}
    /// Set a Method
    fn set_method(&mut self, _method: Method) {}
    /// Set a DatumEnsemble
    fn set_ensemble(&mut self, _ensemble: DatumEnsemble) {}
    /// Set a Member
    fn set_member(&mut self, _member: DatumEnsembleMember) {}
    /// Set an Ellipsoid
    fn set_ellipsoid(&mut self, _ellipsoid: Ellipsoid) {}
    /// Set Accuracy
    fn set_accuracy(&mut self, _accuracy: String) {}
    /// Set Epoch
    fn set_epoch(&mut self, _epoch: f64) {}
    /// Set a frame epoch
    fn set_frame_epoch(&mut self, _epoch: f64) {}
    /// Set a datum
    fn set_datum(&mut self, _datum: Datum) {}
    /// Set a Parameter
    fn set_parameter(&mut self, _parameter: ParameterValue) {}
    /// Set a Meridian
    fn set_meridian(&mut self, _meridian: Meridian) {}
    /// Set a PrimeMeridian
    fn set_prime_meridian(&mut self, _prime_meridian: PrimeMeridian) {}
    /// Set a Conversion
    fn set_conversion(&mut self, _conversion: Conversion) {}
    /// Set a GeodeticCRS
    fn set_geodetic_crs(&mut self, _geodetic_crs: GeodeticCRS) {}
    /// Set a ProjectedCRS
    fn set_projected_crs(&mut self, _projected_crs: ProjectedCRS) {}
    /// Set the name
    fn set_projection(&mut self, _name: String) {}
    /// Set the order
    fn set_order(&mut self, _order: usize) {}
}

/// # Schema for PROJJSON (v0.7)
///
/// ## References
/// - `https://proj.org/schemas/v0.7/projjson.schema.json`
/// - `https://docs.ogc.org/is/18-010r7/18-010r7.html#1`
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum ProjJSON {
    /// Coordinate Reference System
    CRS(Box<CRS>),
    /// Represents a datum which can be one of several types of reference frames or datums.
    Datum(Box<Datum>),
    /// Represents a datum ensemble, which is a collection of datums.
    DatumEnsemble(Box<DatumEnsemble>),
    /// Represents an ellipsoid, a geometric figure used in geodetic reference frames.
    Ellipsoid(Box<Ellipsoid>),
    /// Represents a prime meridian, which defines the origin of longitude in a geographic coordinate system.
    PrimeMeridian(Box<PrimeMeridian>),
    /// Represents a single operation, which can be a conversion, transformation, or point motion operation.
    SingleOperation(Box<SingleOperation>),
    /// Represents an operation that is composed of multiple steps, transforming one CRS to another.
    ConcatenatedOperation(Box<ConcatenatedOperation>),
    /// Represents metadata associated with a coordinate, including its reference system and epoch.
    CoordinateMetadata(Box<CoordinateMetadata>),
}
impl Default for ProjJSON {
    fn default() -> Self {
        ProjJSON::CRS(Box::default())
    }
}
impl ToProjJSON for ProjJSON {
    fn set_id(&mut self, id: Id) {
        match self {
            ProjJSON::CRS(crs) => crs.set_id(id),
            ProjJSON::Datum(datum) => datum.set_id(id),
            ProjJSON::DatumEnsemble(ensemble) => ensemble.set_id(id),
            ProjJSON::PrimeMeridian(prime_meridian) => prime_meridian.set_id(id),
            ProjJSON::Ellipsoid(ellipsoid) => ellipsoid.set_id(id),
            ProjJSON::SingleOperation(operation) => operation.set_id(id),
            ProjJSON::ConcatenatedOperation(operation) => operation.set_id(id),
            ProjJSON::CoordinateMetadata(metadata) => metadata.set_id(id),
        }
    }
    fn set_datum(&mut self, datum: Datum) {
        *self = ProjJSON::Datum(Box::new(datum));
    }
    fn set_ensemble(&mut self, ensemble: DatumEnsemble) {
        *self = ProjJSON::DatumEnsemble(Box::new(ensemble));
    }
    fn set_prime_meridian(&mut self, prime_meridian: PrimeMeridian) {
        *self = ProjJSON::PrimeMeridian(Box::new(prime_meridian));
    }
    fn set_geodetic_crs(&mut self, geodetic_crs: GeodeticCRS) {
        *self = ProjJSON::CRS(Box::new(CRS::GeodeticCRS(Box::new(geodetic_crs))));
    }
    fn set_projected_crs(&mut self, projected_crs: ProjectedCRS) {
        *self = ProjJSON::CRS(Box::new(CRS::ProjectedCRS(Box::new(projected_crs))));
    }
}
impl ProjJSON {
    /// Convert a Proj JSON to a ProjectionTransform (Proj constants with steps)
    pub fn to_projection_transform(&self) -> ProjectionTransform {
        let mut proj_transform = ProjectionTransform::default();
        match self {
            ProjJSON::CRS(crs) => crs.to_projection_transform(&mut proj_transform),
            _ => panic!("Unsupported operation"),
        }

        proj_transform
    }
}

/// Coordinate Reference System
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum CRS {
    /// Represents a coordinate reference system that is bounded by a source and target CRS with a transformation.
    BoundCRS(Box<BoundCRS>),
    /// Represents a compound coordinate reference system, consisting of multiple components.
    CompoundCRS(Box<CompoundCRS>),
    /// Represents a derived engineering coordinate reference system.
    DerivedEngineeringCRS(Box<DerivedEngineeringCRS>),
    /// Represents a derived geodetic or geographic coordinate reference system.
    DerivedGeodeticCRS(Box<DerivedGeodeticCRS>),
    /// Represents a derived parametric coordinate reference system.
    DerivedParametricCRS(Box<DerivedParametricCRS>),
    /// Represents a derived projected coordinate reference system.
    DerivedProjectedCRS(Box<DerivedProjectedCRS>),
    /// Represents a derived temporal coordinate reference system.
    DerivedTemporalCRS(Box<DerivedTemporalCRS>),
    /// Represents a derived vertical coordinate reference system.
    DerivedVerticalCRS(Box<DerivedVerticalCRS>),
    /// Represents an engineering coordinate reference system.
    EngineeringCRS(Box<EngineeringCRS>),
    /// Represents a geodetic or geographic coordinate reference system.
    GeodeticCRS(Box<GeodeticCRS>),
    /// Represents a parametric coordinate reference system.
    ParametricCRS(Box<ParametricCRS>),
    /// Represents a projected coordinate reference system, which transforms geodetic or geographic coordinates
    /// into a flat, two-dimensional plane using a map projection.
    ProjectedCRS(Box<ProjectedCRS>),
    /// Represents a temporal coordinate reference system, which defines time-based coordinates.
    TemporalCRS(Box<TemporalCRS>),
    /// Represents a vertical coordinate reference system, which is used for height or depth measurements.
    VerticalCRS(Box<VerticalCRS>),
}
impl Default for CRS {
    fn default() -> Self {
        CRS::GeodeticCRS(Box::default())
    }
}
impl ToProjJSON for CRS {
    fn set_id(&mut self, id: Id) {
        match self {
            CRS::BoundCRS(crs) => crs.set_id(id),
            CRS::CompoundCRS(crs) => crs.set_id(id),
            CRS::DerivedEngineeringCRS(crs) => crs.set_id(id),
            CRS::DerivedGeodeticCRS(crs) => crs.set_id(id),
            CRS::DerivedParametricCRS(crs) => crs.set_id(id),
            CRS::DerivedProjectedCRS(crs) => crs.set_id(id),
            CRS::DerivedTemporalCRS(crs) => crs.set_id(id),
            CRS::DerivedVerticalCRS(crs) => crs.set_id(id),
            CRS::EngineeringCRS(crs) => crs.set_id(id),
            CRS::GeodeticCRS(crs) => crs.set_id(id),
            CRS::ParametricCRS(crs) => crs.set_id(id),
            CRS::ProjectedCRS(crs) => crs.set_id(id),
            CRS::TemporalCRS(crs) => crs.set_id(id),
            CRS::VerticalCRS(crs) => crs.set_id(id),
        }
    }
    fn set_geodetic_crs(&mut self, geodetic_crs: GeodeticCRS) {
        *self = CRS::GeodeticCRS(geodetic_crs.into());
    }
    fn set_projected_crs(&mut self, projected_crs: ProjectedCRS) {
        *self = CRS::ProjectedCRS(projected_crs.into());
    }
}
impl CRS {
    /// Convert a Proj JSON to a ProjectionTransform (Proj constants with steps)
    pub fn to_projection_transform(&self, proj_transform: &mut ProjectionTransform) {
        match self {
            CRS::GeodeticCRS(crs) => crs.to_projection_transform(proj_transform),
            CRS::ProjectedCRS(crs) => crs.to_projection_transform(proj_transform),
            _ => panic!("Unsupported operation"),
        };
    }
}

/// # Datum Interface
///
/// Represents a datum which can be one of several types of reference frames or datums.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum Datum {
    /// Represents the geodetic reference frame associated with a geodetic CRS.
    GeodeticReferenceFrame(GeodeticReferenceFrame),
    /// Represents the vertical reference frame associated with a vertical CRS.
    VerticalReferenceFrame(VerticalReferenceFrame),
    /// Represents a dynamic geodetic reference frame.
    DynamicGeodeticReferenceFrame(DynamicGeodeticReferenceFrame),
    /// Represents a dynamic vertical reference frame.
    DynamicVerticalReferenceFrame(DynamicVerticalReferenceFrame),
    /// Represents the temporal datum associated with a temporal CRS.
    TemporalDatum(TemporalDatum),
    /// Represents the parametric datum associated with a parametric CRS.
    ParametricDatum(ParametricDatum),
    /// Represents the datum associated with an engineering CRS.
    EngineeringDatum(EngineeringDatum),
}
impl Datum {
    /// Convert a GeodeticCRS to a ProjectionTransform
    pub fn to_projection_transform(&self, proj_transform: &mut ProjectionTransform) {
        // TODO: Implement for all
        match self {
            Datum::GeodeticReferenceFrame(d) => d.to_projection_transform(proj_transform),
            _ => todo!(),
            // Datum::VerticalReferenceFrame(d) => d.to_projection_transform(proj_transform),
            // Datum::DynamicGeodeticReferenceFrame(d) => d.to_projection_transform(proj_transform),
            // Datum::DynamicVerticalReferenceFrame(d) => d.to_projection_transform(proj_transform),
            // Datum::TemporalDatum(d) => d.to_projection_transform(proj_transform),
            // Datum::ParametricDatum(d) => d.to_projection_transform(proj_transform),
            // Datum::EngineeringDatum(d) => d.to_projection_transform(proj_transform),
        };
    }
}
impl Default for Datum {
    fn default() -> Self {
        Datum::GeodeticReferenceFrame(GeodeticReferenceFrame::default())
    }
}
impl ToProjJSON for Datum {
    fn set_id(&mut self, id: Id) {
        match self {
            Datum::GeodeticReferenceFrame(d) => d.set_id(id),
            Datum::VerticalReferenceFrame(d) => d.set_id(id),
            Datum::DynamicGeodeticReferenceFrame(d) => d.set_id(id),
            Datum::DynamicVerticalReferenceFrame(d) => d.set_id(id),
            Datum::TemporalDatum(d) => d.set_id(id),
            Datum::ParametricDatum(d) => d.set_id(id),
            Datum::EngineeringDatum(d) => d.set_id(id),
        }
    }
    fn set_prime_meridian(&mut self, pm: PrimeMeridian) {
        match self {
            Datum::GeodeticReferenceFrame(d) => {
                d.set_prime_meridian(pm);
            }
            Datum::DynamicGeodeticReferenceFrame(d) => {
                d.set_prime_meridian(pm);
            }
            _ => {}
        }
    }
}

/// # Geographic Bounding Box
///
/// ## Description
/// The geographic bounding box is an optional attribute which describes a "north up" area.
/// Upper right latitude will be greater than the lower left latitude. Generally the upper right
/// longitude will be greater than the lower left longitude. However when the area crosses the
/// 180° meridian, the value of the lower left longitude will be greater than the value of the
/// upper right longitude.
///
/// The geographic bounding box is an approximate description of location. For most purposes a
/// coordinate precision of two decimal places of a degree is sufficient. At this resolution the
/// identification of the geodetic CRS to which the bounding box coordinates are referenced is not
/// required.
///
/// ## Requirement
/// Bounding box latitude coordinates shall be given in decimal degrees in the range -90 to +90,
/// longitude coordinates shall be given in decimal degrees in the range -180 to +180 relative to
/// the international reference meridian.
///
/// ## Examples
/// - `BBOX[51.43,2.54,55.77,6.40]`
/// - `BBOX[-55.95,160.60,-25.88,-171.20]`
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct ProjBBox {
    /// The southernmost latitude of the bounding box.
    pub south_latitude: f64,
    /// The westernmost longitude of the bounding box.
    pub west_longitude: f64,
    /// The northernmost latitude of the bounding box.
    pub north_latitude: f64,
    /// The easternmost longitude of the bounding box.
    pub east_longitude: f64,
}

/// # VerticalExtent
///
/// ## Description
/// Vertical extent is an optional attribute which describes a height range over which a CRS or
/// coordinate operation is applicable. Depths have negative height values. Vertical extent is an
/// approximate description of location; heights are relative to an unspecified mean sea level.
///
/// ## Requirement
/// If vertical extent units are not stated they shall be assumed to be metres.
///
/// ## Examples
/// - `VERTICALEXTENT[-1000,0,LENGTHUNIT["metre",1.0]]`
/// - `VERTICALEXTENT[-1000,0]` (where the heights are implicitly in metres).
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct VerticalExtent {
    /// Minimum height
    pub minimum: f64,
    /// Maximum height
    pub maximum: f64,
    /// Unit of measurement
    pub unit: Unit,
}

/// # Temporal Extent
///
/// ## Description
/// Temporal extent is an optional attribute which describes a date or time range over which a CRS
/// or coordinate operation is applicable. The format for date and time values is defined in
/// ISO/IEC 9075-2. Start time is earlier than end time.
///
/// ## Requirement
/// `<temporal extent end>` should have the same data type (dateTime or quoted Latin text) as
/// `<temporal extent start>`.
///
/// ## Examples
/// - `TIMEEXTENT[2013-01-01,2013-12-31]`
/// - `TIMEEXTENT["Jurassic","Quaternary"]`
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct TemporalExtent {
    /// Start time (ISO 8601 format)
    pub start: String,
    /// End time (ISO 8601 format)
    pub end: String,
}

/// String or Number
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ProjValue {
    /// Boolean case
    Bool(bool),
    /// Float case
    F64(f64),
    /// Integer case
    I64(i64),
    /// String case
    String(String),
}
impl Default for ProjValue {
    fn default() -> Self {
        ProjValue::String("".into())
    }
}
impl PartialEq for ProjValue {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (ProjValue::Bool(a), ProjValue::Bool(b)) => a == b,
            (ProjValue::F64(a), ProjValue::F64(b)) => fabs(*a - *b) < f64::EPSILON,
            (ProjValue::I64(a), ProjValue::I64(b)) => a == b,
            (ProjValue::String(a), ProjValue::String(b)) => a == b,
            _ => false,
        }
    }
}
impl ProjValue {
    /// Get the boolean representation
    pub fn bool(&self) -> bool {
        match self {
            ProjValue::Bool(b) => *b,
            ProjValue::F64(f) => *f != 0.0,
            ProjValue::I64(i) => *i != 0,
            ProjValue::String(s) => s.to_lowercase() == "true" || self.i64() != 0,
        }
    }
    /// Get the float representation
    pub fn f64(&self) -> f64 {
        match self {
            ProjValue::Bool(b) => {
                if *b {
                    1.0
                } else {
                    0.0
                }
            }
            ProjValue::F64(f) => *f,
            ProjValue::I64(i) => *i as f64,
            ProjValue::String(s) => s.parse().unwrap_or(0.0),
        }
    }
    /// Get the integer representation
    pub fn i64(&self) -> i64 {
        match self {
            ProjValue::Bool(b) => {
                if *b {
                    1
                } else {
                    0
                }
            }
            ProjValue::F64(f) => *f as i64,
            ProjValue::I64(i) => *i,
            ProjValue::String(s) => s.parse().unwrap_or(0),
        }
    }
    /// Get the string representation
    pub fn string(&self) -> String {
        match self {
            ProjValue::Bool(b) => b.to_string(),
            ProjValue::F64(f) => f.to_string(),
            ProjValue::I64(i) => i.to_string(),
            ProjValue::String(s) => s.clone(),
        }
    }
}
impl From<&str> for ProjValue {
    fn from(v: &str) -> ProjValue {
        ProjValue::String(v.into())
    }
}
impl From<String> for ProjValue {
    fn from(v: String) -> ProjValue {
        ProjValue::String(v)
    }
}
impl From<ProjValue> for String {
    fn from(v: ProjValue) -> String {
        match v {
            ProjValue::String(s) => s,
            _ => "".into(),
        }
    }
}
impl From<f64> for ProjValue {
    fn from(v: f64) -> ProjValue {
        ProjValue::F64(v)
    }
}

/// # Identifier
///
/// ## Description
/// Identifier is an optional attribute which references an external description of the object and
/// which may be applied to a coordinate reference system, a coordinate operation or a bound CRS.
/// Multiple identifiers may be given for any object.
///
/// ## Examples
/// - `ID["Authority name","Abcd_Ef",7.1]`
/// - `ID["EPSG",4326]`
/// - `ID["EPSG",4326,URI["urn:ogc:def:crs:EPSG::4326"]]`
/// - `ID["EuroGeographics","ES_ED50 (BAL99) to ETRS89","2001-04-20"]`
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Id {
    /// Authority issuing the identifier
    pub authority: String,
    /// Code associated with the identifier
    pub code: ProjValue,
    /// Version of the identifier
    /// NOTE: This is not supposed to be optional, but it rarely shows up
    pub version: Option<ProjValue>,
    /// Citation of the authority
    #[serde(skip_serializing_if = "Option::is_none")]
    pub authority_citation: Option<String>,
    /// URI reference
    #[serde(skip_serializing_if = "Option::is_none")]
    pub uri: Option<String>,
}

/// Identifiers list
pub type Ids = Vec<Id>;

/// # Parameter
///
/// ## Description
/// Parameter name is for human readability. For interoperability it is the method formula and its parameters that are critical in determining the equivalence of methods. See Annex F. Identifiers for commonly encountered map projection methods are given in F.2; their parameters are listed in F.3.
///
/// The map projection parameters required are specific to the map projection method and will be listed sequentially. The order within the sequence is not significant but should be logical.
///
/// `<map projection parameter unit>` is an optional attribute, for reasons of backward compatibility. Best practice is that it is included explicitly in WKT strings.
///
/// ## Requirements
/// If `<map projection parameter unit>` is omitted from `<map projection parameter>` then:
/// - Map parameter values that are lengths shall be given in metres.
/// - Map projection parameter values that are angles shall be given in decimal degrees.
/// - Map projection parameters that are unitless (for example scale factor) shall be given as a number which is close to or is unity (1.0).
///
/// ## Examples
/// - `PARAMETER["semi_major",6378137.0]` - Defines a parameter named "semi_major" with a numeric value.
/// - `PARAMETER["towgs84","8,-183,-105,0,0,0,0"]` - Defines a parameter named "towgs84" with a string value.
/// - `PARAMETER["central_meridian",0.0,UNIT["degree",0.0174532925199433]]` - Defines a parameter with a name, numeric value, and a unit.
/// - `PARAMETER["standard_parallel_1",30.0,ID["EPSG",8831]]` - Defines a parameter with a name, numeric value, and an identifier.
/// - `PARAMETER["latitude_of_origin",0.0,UNIT["degree",0.0174532925199433],ID["EPSG",8821]]` - Defines a parameter with a name, numeric value, unit, and identifier.
/// - `PARAMETER["is_sphere",TRUE]` - Defines a boolean parameter.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct ParameterValue {
    /// Schema reference
    #[serde(rename = "$schema", skip_serializing_if = "Option::is_none")]
    pub schema: Option<String>,
    /// Type identifier - always 'ParameterValue'
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'ParameterValue';
    /// Name of the parameter
    pub name: String,
    /// Parameter value, which can be a string or number
    pub value: ProjValue,
    /// Optional unit of measurement
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unit: Option<Unit>,
    /// Identifier
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<Id>,
    /// Alternative identifiers
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub ids: Ids,
    /// NOT PART OF SPEC
    pub is_file: bool,
}
impl ParameterValue {
    /// Get the radians of the value
    pub fn rad(&self) -> f64 {
        // If no unit, build from name_to_unit, if angle, it's degree, otherwise metre
        let unit = self.unit.clone().unwrap_or_else(|| name_to_unit(&self.name));
        self.value.f64() * unit.rad()
    }
}
impl From<&ParameterValue> for ProjValue {
    fn from(p_value: &ParameterValue) -> Self {
        ProjValue::F64(p_value.rad())
    }
}
impl ToProjJSON for ParameterValue {
    fn set_id(&mut self, id: Id) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if !self.ids.is_empty() {
            self.ids.push(id);
        } else if let Some(i) = self.id.clone() {
            self.ids.extend(vec![i, id]);
            self.id = None;
        } else {
            self.id = Some(id);
        }
    }
    fn set_unit(&mut self, unit: Unit) {
        self.unit = Some(unit);
    }
}

/// # Parametric CRS
///
/// Represents a parametric coordinate reference system.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct ParametricCRS {
    /// Type identifier - always 'ParametricCRS'
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'ParametricCRS';
    /// Name of the CRS
    pub name: String,
    /// Parametric datum
    pub datum: ParametricDatum,
    /// Coordinate system
    pub coordinate_system: Option<CoordinateSystem>,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for ParametricCRS {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_coordinate_system(&mut self, cs: CoordinateSystem) {
        self.coordinate_system = Some(cs);
    }
    // Pass down to the coordinate system
    fn set_axis(&mut self, axis: Axis) {
        if let Some(ref mut cs) = self.coordinate_system {
            cs.axis.push(axis);
        }
    }
    fn set_unit(&mut self, unit: Unit) {
        if let Some(ref mut cs) = self.coordinate_system {
            for axis in cs.axis.iter_mut() {
                axis.unit = Some(unit.clone());
            }
        }
    }
}

/// # Parametric Datum
///
/// Represents the parametric datum associated with a parametric CRS.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct ParametricDatum {
    /// Type identifier - always 'ParametricDatum'
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'ParametricDatum';
    /// Name of the datum
    pub name: String,
    /// Anchor point
    pub anchor: String,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for ParametricDatum {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_anchor(&mut self, anchor: String) {
        self.anchor = anchor;
    }
}

/// # Point Motion Operation
///
/// Represents a point motion operation
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct PointMotionOperation {
    /// Type identifier
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'PointMotionOperation';
    /// Name of the operation
    pub name: String,
    /// Source coordinate reference system
    pub source_crs: CRS,
    /// Method used for point motion
    pub method: Method,
    /// Parameters used in the operation
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub parameters: Vec<ParameterValue>,
    /// Accuracy of the operation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub accuracy: Option<String>,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for PointMotionOperation {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_accuracy(&mut self, accuracy: String) {
        self.accuracy = Some(accuracy);
    }
    fn set_projection(&mut self, name: String) {
        self.method = Method { name, ..Default::default() };
    }
    fn set_method(&mut self, method: Method) {
        self.method = method;
    }
    fn set_parameter(&mut self, parameter: ParameterValue) {
        self.parameters.push(parameter);
    }
}

/// # Method Object
///
/// Defines an operation method with a name and identifier
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Method {
    /// Schema reference
    #[serde(rename = "$schema", skip_serializing_if = "Option::is_none")]
    pub schema: Option<String>,
    /// Type identifier - always 'OperationMethod'
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'OperationMethod';
    /// Name of the method
    pub name: String,
    /// Identifier
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<Id>,
    /// Alternative identifiers
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub ids: Ids,
}
impl Method {
    /// Convert a Method to a ProjectionTransform
    pub fn to_projection_transform(&self, proj_transform: &mut ProjectionTransform) {
        // add projection from method
        proj_transform.method = Step::from_method(self, proj_transform.proj.clone()).unwrap();
    }
}
impl ToProjJSON for Method {
    fn set_id(&mut self, id: Id) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if !self.ids.is_empty() {
            self.ids.push(id);
        } else if let Some(i) = self.id.clone() {
            self.ids.extend(vec![i, id]);
            self.id = None;
        } else {
            self.id = Some(id);
        }
    }
}

/// Base Unit - common units as string input
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
pub enum BaseUnit {
    /// Metre
    #[serde(rename = "metre")]
    #[default]
    Metre,
    /// Degree
    #[serde(rename = "degree")]
    Degree,
    /// Unity
    #[serde(rename = "unity")]
    Unity,
}

/// Unit Type - String input
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "PascalCase")]
pub enum UnitType {
    /// Linear
    LinearUnit,
    /// Angular
    AngularUnit,
    /// Scale
    ScaleUnit,
    /// Time
    TimeUnit,
    /// Parametric
    ParametricUnit,
    /// Unit
    #[default]
    Unit,
}
impl From<&str> for UnitType {
    fn from(s: &str) -> Self {
        match s {
            "LENGTHUNIT" => UnitType::LinearUnit,
            "ANGLEUNIT" => UnitType::AngularUnit,
            "SCALEUNIT" => UnitType::ScaleUnit,
            "TIMEUNIT" => UnitType::TimeUnit,
            "PARAMETRICUNIT" => UnitType::ParametricUnit,
            _ => UnitType::Unit, // UNIT
        }
    }
}

/// Unit Object
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct UnitObject {
    /// Type of unit
    #[serde(rename = "type")]
    pub r#type: UnitType,
    /// Name of the unit
    pub name: String,
    /// Conversion factor
    #[serde(skip_serializing_if = "Option::is_none")]
    pub conversion_factor: Option<f64>,
    /// Schema reference
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<Id>,
    /// Alternative identifiers
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub ids: Ids,
}
impl UnitObject {
    /// Set the unit type
    pub fn set_unit_type(&mut self, unit_type: UnitType) {
        self.r#type = unit_type;
    }
    /// Convert to Radian
    pub fn rad(&self) -> f64 {
        match self.r#type {
            UnitType::AngularUnit => self.conversion_factor.unwrap_or(1.0),
            _ => 1.0,
        }
    }
    /// Convert to Meters
    pub fn meters(&self) -> f64 {
        match self.r#type {
            UnitType::LinearUnit => self.conversion_factor.unwrap_or(1.0),
            _ => 1.0,
        }
    }
}
impl ToProjJSON for UnitObject {
    fn set_id(&mut self, id: Id) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if !self.ids.is_empty() {
            self.ids.push(id);
        } else if let Some(i) = self.id.clone() {
            self.ids.extend(vec![i, id]);
            self.id = None;
        } else {
            self.id = Some(id);
        }
    }
}

/// # Unit
///
/// ## Description
/// Defines the unit of measure for lengths or distances, typically used within other spatial
/// extent definitions like `VerticalExtent`. It consists of a unit name (e.g., "metre", "foot")
/// and a corresponding numeric value, often representing the conversion factor to a base unit.
///
/// ## Common naming convention
/// - LENGTHUNIT
/// - ANGLEUNIT
/// - SCALEUNIT
/// - TIMEUNIT
/// - PARAMETRICUNIT
///
/// ## Requirement
/// The WKT representation of a `<length unit>` shall be:
/// ```bnf
/// <length unit> ::= <length unit keyword> <left delimiter> <quoted text> <wkt separator> <number> <right delimiter>
/// <length unit keyword> ::= LENGTHUNIT
/// ```
///
/// Unprovided defaults to BaseUnit->Metre
///
/// ## Examples
/// - `LENGTHUNIT["metre",1.0]`
/// - `LENGTHUNIT["foot",0.3048]`
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum Unit {
    /// Base case
    BaseUnit(BaseUnit),
    /// Object with complex units
    UnitObject(UnitObject),
}
impl Default for Unit {
    fn default() -> Self {
        Unit::BaseUnit(BaseUnit::default())
    }
}
impl Unit {
    /// Create a degree unit
    pub fn new_deg() -> Self {
        Unit::BaseUnit(BaseUnit::Degree)
    }
    /// Set the unit type assuming the unit is a UnitObject
    pub fn set_unit_type(&mut self, unit_type: UnitType) {
        match self {
            Unit::BaseUnit(_) => {}
            Unit::UnitObject(unit) => unit.set_unit_type(unit_type),
        };
    }
    /// Get the multiplier for the unit to convert to radians
    pub fn rad(&self) -> f64 {
        match self {
            Unit::BaseUnit(unit) => match unit {
                BaseUnit::Metre => 1.0,
                BaseUnit::Degree => core::f64::consts::PI / 180.0,
                BaseUnit::Unity => 1.0,
            },
            Unit::UnitObject(unit) => unit.rad(),
        }
    }
    /// Get the multiplier for the unit to convert to meters
    pub fn meters(&self) -> f64 {
        match self {
            Unit::BaseUnit(unit) => match unit {
                BaseUnit::Metre => 1.0,
                BaseUnit::Degree => core::f64::consts::PI / 180.0,
                BaseUnit::Unity => 1.0,
            },
            Unit::UnitObject(unit) => unit.meters(),
        }
    }
}
impl ToProjJSON for Unit {
    fn set_unit(&mut self, unit: Unit) {
        *self = unit
    }
}

/// # BoundCRS Interface
///
/// Represents a coordinate reference system that is bounded by a source and target CRS with a transformation.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct BoundCRS {
    /// Indicates the type of object. Always "BoundCRS" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>,
    /// The name of the bound CRS.
    pub name: Option<String>,
    /// The source coordinate reference system.
    pub source_crs: Box<CRS>,
    /// The target coordinate reference system.
    pub target_crs: Box<CRS>,
    /// The transformation applied to convert between the source and target CRS.
    pub transformation: AbridgedTransformation,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for BoundCRS {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
}

/// # ConcatenatedOperation Interface
///
/// Represents an operation that is composed of multiple steps, transforming one CRS to another.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct ConcatenatedOperation {
    /// Indicates the type of object. Always "ConcatenatedOperation" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'ConcatenatedOperation';
    /// The name of the concatenated operation.
    pub name: String,
    /// The source coordinate reference system.
    pub source_crs: CRS,
    /// The target coordinate reference system.
    pub target_crs: CRS,
    /// An array of individual steps in the concatenated operation.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub steps: Vec<SingleOperation>,
    /// The accuracy of the concatenated operation.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub accuracy: Option<String>,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for ConcatenatedOperation {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_accuracy(&mut self, accuracy: String) {
        self.accuracy = Some(accuracy);
    }
}

/// # AbridgedTransformation Interface
///
/// Represents an abridged transformation used for converting between different coordinate reference systems.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct AbridgedTransformation {
    /// The schema URL or identifier.
    #[serde(rename = "$schema", skip_serializing_if = "Option::is_none")]
    pub schema: Option<String>,
    /// Indicates the type of object. Always "AbridgedTransformation" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'AbridgedTransformation';
    /// The name of the transformation.
    pub name: String,
    /// The source coordinate reference system, only present if it differs from the source CRS of the bound CRS.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub source_crs: Option<Box<CRS>>,
    /// The method used for the transformation.
    pub method: Method,
    /// The parameters used in the transformation.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub parameters: Vec<ParameterValue>,
    /// An identifier for the axis.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<Id>,
    /// An array of identifiers for the axis.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub ids: Ids,
}
impl ToProjJSON for AbridgedTransformation {
    fn set_projection(&mut self, name: String) {
        self.method = Method { name, ..Default::default() };
    }
    fn set_method(&mut self, method: Method) {
        self.method = method;
    }
    fn set_parameter(&mut self, parameter: ParameterValue) {
        self.parameters.push(parameter);
    }
    fn set_id(&mut self, id: Id) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if !self.ids.is_empty() {
            self.ids.push(id);
        } else if let Some(i) = self.id.clone() {
            self.ids.extend(vec![i, id]);
            self.id = None;
        } else {
            self.id = Some(id);
        }
    }
}

/// # CompoundCRS Interface
///
/// Represents a compound coordinate reference system, consisting of multiple components.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct CompoundCRS {
    /// Indicates the type of object. Always "CompoundCRS" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'CompoundCRS';
    /// The name of the compound CRS.
    pub name: String,
    /// An array of coordinate reference systems that make up the compound CRS.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub components: Vec<CRS>,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for CompoundCRS {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
}

/// # EngineeringCRS Interface
///
/// Represents an engineering coordinate reference system.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct EngineeringCRS {
    /// Indicates the type of CRS. Always "EngineeringCRS" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'EngineeringCRS';
    /// The name of the engineering CRS.
    pub name: String,
    /// The engineering datum associated with this CRS.
    pub datum: EngineeringDatum,
    /// The coordinate system used in this CRS.
    pub coordinate_system: Option<CoordinateSystem>,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for EngineeringCRS {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_coordinate_system(&mut self, cs: CoordinateSystem) {
        self.coordinate_system = Some(cs);
    }
    // Pass down to the coordinate system
    fn set_axis(&mut self, axis: Axis) {
        if let Some(ref mut cs) = self.coordinate_system {
            cs.axis.push(axis);
        }
    }
    fn set_unit(&mut self, unit: Unit) {
        if let Some(ref mut cs) = self.coordinate_system {
            for axis in cs.axis.iter_mut() {
                axis.unit = Some(unit.clone());
            }
        }
    }
}

/// # EngineeringDatum Interface
///
/// Represents the datum associated with an engineering CRS.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct EngineeringDatum {
    /// Indicates the type of datum. Always "EngineeringDatum" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'EngineeringDatum';
    /// The name of the datum.
    pub name: String,
    /// Anchor point of the datum.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub anchor: Option<String>,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for EngineeringDatum {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_anchor(&mut self, anchor: String) {
        self.anchor = Some(anchor);
    }
}

/// Axis Direction defines an axis direction
#[derive(Debug, Default, Clone, Copy, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum AxisDirection {
    /// North
    North,
    /// North by North East
    NorthNorthEast,
    /// North East
    NorthEast,
    /// East by North East
    EastNorthEast,
    /// East
    East,
    /// East by South East
    EastSouthEast,
    /// South East
    SouthEast,
    /// South by South East
    SouthSouthEast,
    /// South
    South,
    /// South by South West
    SouthSouthWest,
    /// South West
    SouthWest,
    /// West by South West
    WestSouthWest,
    /// West
    West,
    /// West by North West
    WestNorthWest,
    /// North West
    NorthWest,
    /// North by North West
    NorthNorthWest,
    /// Up
    Up,
    /// Down
    Down,
    /// Geocentric X
    GeocentricX,
    /// Geocentric Y
    GeocentricY,
    /// Geocentric Z
    GeocentricZ,
    /// Column Positive
    ColumnPositive,
    /// Column Negative
    ColumnNegative,
    /// Row Positive
    RowPositive,
    /// Row Negative
    RowNegative,
    /// Display Right
    DisplayRight,
    /// Display Left
    DisplayLeft,
    /// Display Up
    DisplayUp,
    /// Display Down
    DisplayDown,
    /// Forward
    Forward,
    /// Aft
    Aft,
    /// Port
    Port,
    /// Starboard
    Starboard,
    /// Clockwise
    Clockwise,
    /// Counter Clockwise
    CounterClockwise,
    /// Towards
    Towards,
    /// Away From
    AwayFrom,
    /// Future
    Future,
    /// Past
    Past,
    /// Unspecified
    #[default]
    Unspecified,
}
impl From<String> for AxisDirection {
    fn from(s: String) -> Self {
        serde_json::from_str(&format!("\"{}\"", &s))
            .or_else(|_| serde_json::from_str(&format!("\"{}\"", to_camel_case(&s))))
            .unwrap_or_else(|_| {
                // try a few cases otherwise default
                match s.to_lowercase().as_str() {
                    "n" => AxisDirection::North,
                    "ne" | "northeast" => AxisDirection::NorthEast,
                    "e" => AxisDirection::East,
                    "se" | "southeast" => AxisDirection::SouthEast,
                    "s" => AxisDirection::South,
                    "sw" | "southwest" => AxisDirection::SouthWest,
                    "w" => AxisDirection::West,
                    "nw" | "northwest" => AxisDirection::NorthWest,
                    _ => AxisDirection::Unspecified,
                }
            })
    }
}

/// Axis Range Meaning
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum AxisRangeMeaning {
    /// Exact
    #[default]
    Exact,
    /// Wraparound
    Wraparound,
}

/// # Axis Interface
///
/// Represents an individual axis in a coordinate system.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Axis {
    /// Indicates the type of axis. Always "Axis" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'Axis';
    /// The name of the axis.
    pub name: String,
    /// Abbreviation for the axis name.
    pub abbreviation: String,
    /// The direction of the axis.
    /// Examples include north, east, up, down, geocentricX, geocentricY, geocentricZ, etc.
    pub direction: AxisDirection,
    /// The order of the axis.
    /// Not part of the specification, added for convenience.
    pub order: usize,
    /// The meridian for the axis, if applicable.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub meridian: Option<Meridian>,
    /// The unit of measurement for the axis.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub unit: Option<Unit>,
    /// The minimum value allowed for the axis.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub minimum_value: Option<f64>,
    /// The maximum value allowed for the axis.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub maximum_value: Option<f64>,
    /// The range meaning for the axis.
    /// Can be either "exact" or "wraparound".
    #[serde(skip_serializing_if = "Option::is_none")]
    pub range_meaning: Option<AxisRangeMeaning>,
    /// An identifier for the axis.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<Id>,
    /// An array of identifiers for the axis.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub ids: Ids,
}
impl Axis {
    /// Adjust the order if needed
    pub fn adjust_if_needed(&mut self) {
        if self.order != 0 {
            return;
        }
        let name = self.name.to_lowercase();
        self.order = if name.contains("longitude")
            || name.contains("northing")
            || name.contains("(lon)")
            || name.contains("(Y)")
            || name.contains("(N)")
        {
            2
        } else if name.contains("z") {
            3
        } else {
            0
        };
    }
}
impl ToProjJSON for Axis {
    fn set_id(&mut self, id: Id) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if !self.ids.is_empty() {
            self.ids.push(id);
        } else if let Some(i) = self.id.clone() {
            self.ids.extend(vec![i, id]);
            self.id = None;
        } else {
            self.id = Some(id);
        }
    }
    fn set_unit(&mut self, unit: Unit) {
        self.unit = Some(unit);
    }
    fn set_meridian(&mut self, meridian: Meridian) {
        self.meridian = Some(meridian);
    }
    fn set_order(&mut self, order: usize) {
        self.order = order;
    }
}

/// # Meridian Interface
///
/// Represents a meridian, which defines the longitude for an axis.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Meridian {
    /// The schema URL or identifier.
    #[serde(rename = "$schema", skip_serializing_if = "Option::is_none")]
    pub schema: Option<String>,
    /// Indicates the type of meridian. Always "Meridian" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'Meridian';
    /// The longitude of the meridian.
    pub longitude: ValueInDegreeOrValueAndUnit,
    /// An identifier for the meridian.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<Id>,
    /// An array of identifiers for the meridian.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub ids: Ids,
}
impl ToProjJSON for Meridian {
    fn set_id(&mut self, id: Id) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if !self.ids.is_empty() {
            self.ids.push(id);
        } else if let Some(i) = self.id.clone() {
            self.ids.extend(vec![i, id]);
            self.id = None;
        } else {
            self.id = Some(id);
        }
    }
}

/// # ValueAndUnit Interface
///
/// Represents a value paired with a unit of measurement.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct ValueAndUnit {
    /// The numeric degree value.
    pub value: f64,
    /// The unit of measurement.
    pub unit: Unit,
}
impl ValueAndUnit {
    /// Get the radians of the value
    pub fn rad(&self) -> f64 {
        self.value * self.unit.rad()
    }
}

/// Value in Degrees or Value and Unit
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum ValueInDegreeOrValueAndUnit {
    /// Float value (degrees)
    F64(f64),
    /// Value and Unit Object
    ValueAndUnit(ValueAndUnit),
}
impl ValueInDegreeOrValueAndUnit {
    /// Create a new `ValueInDegreeOrValueAndUnit` from a unit and value
    pub fn from_unit(unit: Unit, value: f64) -> Self {
        ValueInDegreeOrValueAndUnit::ValueAndUnit(ValueAndUnit { value, unit })
    }
    /// Get the radians of the value
    pub fn rad(&self) -> f64 {
        match self {
            ValueInDegreeOrValueAndUnit::F64(value) => (*value).to_radians(),
            ValueInDegreeOrValueAndUnit::ValueAndUnit(value) => value.rad(),
        }
    }
}
impl Default for ValueInDegreeOrValueAndUnit {
    fn default() -> Self {
        ValueInDegreeOrValueAndUnit::F64(0.0)
    }
}
impl ToProjJSON for ValueInDegreeOrValueAndUnit {
    fn set_unit(&mut self, unit: Unit) {
        match self {
            ValueInDegreeOrValueAndUnit::F64(val) => {
                *self =
                    ValueInDegreeOrValueAndUnit::ValueAndUnit(ValueAndUnit { value: *val, unit });
            }
            ValueInDegreeOrValueAndUnit::ValueAndUnit(value) => value.unit = unit,
        }
    }
}

/// Value in Metres or Value and Unit
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum ValueInMetreOrValueAndUnit {
    /// Float
    F64(f64),
    /// Value and Unit
    ValueAndUnit(ValueAndUnit),
}
impl ValueInMetreOrValueAndUnit {
    /// Create a new `ValueInMetreOrValueAndUnit` from a unit and value
    pub fn from_unit(unit: Unit, value: f64) -> Self {
        ValueInMetreOrValueAndUnit::ValueAndUnit(ValueAndUnit { value, unit })
    }
    /// Get the meters of the value
    pub fn meters(&self) -> f64 {
        match self {
            ValueInMetreOrValueAndUnit::F64(value) => *value,
            ValueInMetreOrValueAndUnit::ValueAndUnit(value) => value.unit.meters() * value.value,
        }
    }
}
impl Default for ValueInMetreOrValueAndUnit {
    fn default() -> Self {
        ValueInMetreOrValueAndUnit::F64(0.0)
    }
}
impl From<f64> for ValueInMetreOrValueAndUnit {
    fn from(value: f64) -> Self {
        ValueInMetreOrValueAndUnit::F64(value)
    }
}

/// # Single Operation
///
/// Represents a single operation, which can be a conversion, transformation, or point motion operation.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum SingleOperation {
    /// Conversion Operation
    Conversion(Box<Conversion>),
    /// Transformation Operation
    Transformation(Box<Transformation>),
    /// Point & Motion Operation
    PointMotionOperation(Box<PointMotionOperation>),
}
impl ToProjJSON for SingleOperation {
    fn set_id(&mut self, id: Id) {
        match self {
            SingleOperation::Conversion(c) => c.set_id(id),
            SingleOperation::Transformation(t) => t.set_id(id),
            SingleOperation::PointMotionOperation(p) => p.set_id(id),
        }
    }
    fn set_conversion(&mut self, conversion: Conversion) {
        *self = SingleOperation::Conversion(Box::new(conversion));
    }
}

/// # DeformationModel Interface
///
/// Represents a deformation model associated with a point motion operation.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct DeformationModel {
    /// The name of the deformation model.
    pub name: String,
    /// An identifier for the deformation model.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<Id>,
}

/// # DerivedEngineeringCRS Interface
///
/// Represents a derived engineering coordinate reference system.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct DerivedEngineeringCRS {
    /// Indicates the type of coordinate reference system. Always "DerivedEngineeringCRS" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'DerivedEngineeringCRS';
    /// The name of the derived engineering CRS.
    pub name: String,
    /// The base CRS from which this derived CRS is created.
    pub base_crs: EngineeringCRS,
    /// The conversion method applied to the base CRS.
    pub conversion: Conversion,
    /// The coordinate system used in the CRS.
    pub coordinate_system: CoordinateSystem,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for DerivedEngineeringCRS {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_coordinate_system(&mut self, cs: CoordinateSystem) {
        self.coordinate_system = cs;
    }
    fn set_conversion(&mut self, conversion: Conversion) {
        self.conversion = conversion;
    }
    // Pass down to the coordinate system
    fn set_axis(&mut self, axis: Axis) {
        self.coordinate_system.axis.push(axis);
    }
    fn set_unit(&mut self, unit: Unit) {
        for axis in self.coordinate_system.axis.iter_mut() {
            axis.unit = Some(unit.clone());
        }
    }
}

/// # DerivedGeodeticCRS Interface
///
/// Represents a derived geodetic or geographic coordinate reference system.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct DerivedGeodeticCRS {
    /// Indicates the type of coordinate reference system. Can be either "DerivedGeodeticCRS" or "DerivedGeographicCRS".
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'DerivedGeodeticCRS' | 'DerivedGeographicCRS';
    /// The name of the derived geodetic CRS.
    pub name: String,
    /// The base CRS from which this derived CRS is created.
    pub base_crs: GeodeticCRS,
    /// The conversion method applied to the base CRS.
    pub conversion: Conversion,
    /// The coordinate system used in the CRS.
    pub coordinate_system: CoordinateSystem,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for DerivedGeodeticCRS {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_coordinate_system(&mut self, cs: CoordinateSystem) {
        self.coordinate_system = cs;
    }
    fn set_conversion(&mut self, conversion: Conversion) {
        self.conversion = conversion;
    }
    fn set_geodetic_crs(&mut self, geodetic_crs: GeodeticCRS) {
        self.base_crs = geodetic_crs;
    }
    // Pass down to the coordinate system
    fn set_axis(&mut self, axis: Axis) {
        self.coordinate_system.axis.push(axis);
    }
    fn set_unit(&mut self, unit: Unit) {
        for axis in self.coordinate_system.axis.iter_mut() {
            axis.unit = Some(unit.clone());
        }
    }
}

/// # GeodeticCRS Interface
///
/// Represents a geodetic or geographic coordinate reference system.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct GeodeticCRS {
    /// Indicates the type of CRS. Can be "GeodeticCRS" or "GeographicCRS".
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'GeodeticCRS' | 'GeographicCRS';
    /// The name of the geodetic CRS.
    pub name: String,
    /// The datum associated with the geodetic CRS.
    /// One and only one of `datum` or `datum_ensemble` must be provided.
    /// Can only be `GeodeticReferenceFrame` or `DynamicGeodeticReferenceFrame`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub datum: Option<Datum>,
    /// The datum ensemble associated with the geodetic CRS.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub datum_ensemble: Option<DatumEnsemble>,
    /// The coordinate system used in the geodetic CRS.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub coordinate_system: Option<CoordinateSystem>,
    /// An array of deformation models associated with the geodetic CRS.
    /// DYNAMIC[FRAMEEPOCH[2010.0],MODEL["NAD83(CSRS)v6 velocity grid"]] (referenced by MODEL)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deformation_models: Option<Vec<DeformationModel>>,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for GeodeticCRS {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_coordinate_system(&mut self, cs: CoordinateSystem) {
        self.coordinate_system = Some(cs);
    }
    fn set_datum(&mut self, datum: Datum) {
        self.datum = Some(datum);
    }
    fn set_ensemble(&mut self, ensemble: DatumEnsemble) {
        self.datum_ensemble = Some(ensemble);
    }
    // Pass down to the datum
    fn set_prime_meridian(&mut self, prime_meridian: PrimeMeridian) {
        if let Some(ref mut datum) = self.datum {
            datum.set_prime_meridian(prime_meridian);
        }
    }
    // Pass down to the coordinate system
    fn set_axis(&mut self, axis: Axis) {
        if let Some(ref mut cs) = self.coordinate_system {
            cs.axis.push(axis);
        }
    }
    fn set_unit(&mut self, unit: Unit) {
        if let Some(ref mut cs) = self.coordinate_system {
            for axis in cs.axis.iter_mut() {
                axis.unit = Some(unit.clone());
            }
        }
    }
}
impl GeodeticCRS {
    /// Convert a GeodeticCRS to a ProjectionTransform
    pub fn to_projection_transform(&self, proj_transform: &mut ProjectionTransform) {
        proj_transform.proj.borrow_mut().name = self.name.clone();
        // TODO: DeformationModel
        // TODO: Datum -> build_datum
        if let Some(datum_ensemble) = &self.datum_ensemble {
            datum_ensemble.to_projection_transform(proj_transform);
        }
        if let Some(datum) = &self.datum {
            datum.to_projection_transform(proj_transform);
        }
        if let Some(coordinate_system) = &self.coordinate_system {
            coordinate_system.to_projection_transform(proj_transform);
        }
    }
}

/// # Geodetic reference frame (geodetic datum)
///
/// Represented with the `DATUM` keyword
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct GeodeticReferenceFrame {
    /// Indicates the type of reference frame. Always "GeodeticReferenceFrame" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'GeodeticReferenceFrame';
    /// The name of the reference frame.
    pub name: String,
    /// The ellipsoid used in the reference frame.
    pub ellipsoid: Ellipsoid,
    /// The anchor point of the reference frame.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub anchor: Option<String>,
    /// The epoch of the anchor point.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub anchor_epoch: Option<f64>,
    /// The prime meridian associated with the reference frame.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prime_meridian: Option<PrimeMeridian>,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl GeodeticReferenceFrame {
    /// Convert a GeodeticReferenceFrame to a ProjectionTransform
    pub fn to_projection_transform(&self, proj_transform: &mut ProjectionTransform) {
        self.ellipsoid.to_projection_transform(proj_transform);
        if let Some(pm) = &self.prime_meridian {
            pm.to_projection_transform(proj_transform);
        }
    }
}
impl ToProjJSON for GeodeticReferenceFrame {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_anchor(&mut self, anchor: String) {
        self.anchor = Some(anchor);
    }
    fn set_ellipsoid(&mut self, ellipsoid: Ellipsoid) {
        self.ellipsoid = ellipsoid;
    }
    fn set_epoch(&mut self, epoch: f64) {
        self.anchor_epoch = Some(epoch);
    }
    fn set_prime_meridian(&mut self, prime_meridian: PrimeMeridian) {
        self.prime_meridian = Some(prime_meridian);
    }
}

/// # DerivedParametricCRS Interface
///
/// Represents a derived parametric coordinate reference system.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct DerivedParametricCRS {
    /// Indicates the type of coordinate reference system. Always "DerivedParametricCRS" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'DerivedParametricCRS';
    /// The name of the derived parametric CRS.
    pub name: String,
    /// The base parametric CRS from which this CRS is derived.
    pub base_crs: ParametricCRS,
    /// The conversion method applied to the base CRS.
    pub conversion: Conversion,
    /// The coordinate system used in the CRS.
    pub coordinate_system: CoordinateSystem,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for DerivedParametricCRS {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_coordinate_system(&mut self, cs: CoordinateSystem) {
        self.coordinate_system = cs;
    }
    fn set_conversion(&mut self, conversion: Conversion) {
        self.conversion = conversion;
    }
    // Pass down to the coordinate system
    fn set_axis(&mut self, axis: Axis) {
        self.coordinate_system.axis.push(axis);
    }
    fn set_unit(&mut self, unit: Unit) {
        for axis in self.coordinate_system.axis.iter_mut() {
            axis.unit = Some(unit.clone());
        }
    }
}

/// # DerivedProjectedCRS Interface
///
/// Represents a derived projected coordinate reference system.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct DerivedProjectedCRS {
    /// Indicates the type of coordinate reference system. Always "DerivedProjectedCRS" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'DerivedProjectedCRS';
    /// The name of the derived projected CRS.
    pub name: String,
    /// The base projected CRS from which this CRS is derived.
    pub base_crs: ProjectedCRS,
    /// The conversion method applied to the base CRS.
    pub conversion: Conversion,
    /// The coordinate system used in the CRS.
    pub coordinate_system: CoordinateSystem,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for DerivedProjectedCRS {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_coordinate_system(&mut self, cs: CoordinateSystem) {
        self.coordinate_system = cs;
    }
    fn set_conversion(&mut self, conversion: Conversion) {
        self.conversion = conversion;
    }
    fn set_projected_crs(&mut self, projected_crs: ProjectedCRS) {
        self.base_crs = projected_crs;
    }
    // Pass down to the coordinate system
    fn set_axis(&mut self, axis: Axis) {
        self.coordinate_system.axis.push(axis);
    }
    fn set_unit(&mut self, unit: Unit) {
        for axis in self.coordinate_system.axis.iter_mut() {
            axis.unit = Some(unit.clone());
        }
    }
}

/// # DerivedTemporalCRS Interface
///
/// Represents a derived temporal coordinate reference system.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct DerivedTemporalCRS {
    /// Indicates the type of coordinate reference system. Always "DerivedTemporalCRS" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'DerivedTemporalCRS';
    /// The name of the derived temporal CRS.
    pub name: String,
    /// The base temporal CRS from which this CRS is derived.
    pub base_crs: TemporalCRS,
    /// The conversion method applied to the base CRS.
    pub conversion: Conversion,
    /// The coordinate system used in the CRS.
    pub coordinate_system: CoordinateSystem,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for DerivedTemporalCRS {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_coordinate_system(&mut self, cs: CoordinateSystem) {
        self.coordinate_system = cs;
    }
    fn set_conversion(&mut self, conversion: Conversion) {
        self.conversion = conversion;
    }
    // Pass down to the coordinate system
    fn set_axis(&mut self, axis: Axis) {
        self.coordinate_system.axis.push(axis);
    }
    fn set_unit(&mut self, unit: Unit) {
        for axis in self.coordinate_system.axis.iter_mut() {
            axis.unit = Some(unit.clone());
        }
    }
}

/// # DerivedVerticalCRS Interface
///
/// Represents a derived vertical coordinate reference system.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct DerivedVerticalCRS {
    /// Indicates the type of coordinate reference system. Always "DerivedVerticalCRS" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'DerivedVerticalCRS';
    /// The name of the derived vertical CRS.
    pub name: String,
    /// The base vertical CRS from which this CRS is derived.
    pub base_crs: VerticalCRS,
    /// The conversion method applied to the base CRS.
    pub conversion: Conversion,
    /// The coordinate system used in the CRS.
    pub coordinate_system: CoordinateSystem,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for DerivedVerticalCRS {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_coordinate_system(&mut self, cs: CoordinateSystem) {
        self.coordinate_system = cs;
    }
    fn set_conversion(&mut self, conversion: Conversion) {
        self.conversion = conversion;
    }
    // Pass down to the coordinate system
    fn set_axis(&mut self, axis: Axis) {
        self.coordinate_system.axis.push(axis);
    }
    fn set_unit(&mut self, unit: Unit) {
        for axis in self.coordinate_system.axis.iter_mut() {
            axis.unit = Some(unit.clone());
        }
    }
}

/// # DynamicGeodeticReferenceFrame Interface
///
/// Represents a dynamic geodetic reference frame.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct DynamicGeodeticReferenceFrame {
    /// Indicates the type of reference frame. Always "DynamicGeodeticReferenceFrame" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'DynamicGeodeticReferenceFrame';
    /// The name of the reference frame.
    pub name: String,
    /// The ellipsoid used in the reference frame.
    pub ellipsoid: Ellipsoid,
    /// The frame reference epoch.
    pub frame_reference_epoch: f64,
    /// The anchor point of the reference frame.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub anchor: Option<String>,
    /// The epoch of the anchor point.
    pub anchor_epoch: Option<f64>,
    /// The prime meridian associated with the reference frame.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prime_meridian: Option<PrimeMeridian>,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for DynamicGeodeticReferenceFrame {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_anchor(&mut self, anchor: String) {
        self.anchor = Some(anchor);
    }
    fn set_epoch(&mut self, epoch: f64) {
        self.anchor_epoch = Some(epoch);
    }
    fn set_frame_epoch(&mut self, epoch: f64) {
        self.frame_reference_epoch = epoch;
    }
    fn set_ellipsoid(&mut self, ellipsoid: Ellipsoid) {
        self.ellipsoid = ellipsoid;
    }
    fn set_prime_meridian(&mut self, prime_meridian: PrimeMeridian) {
        self.prime_meridian = Some(prime_meridian);
    }
}

/// members in the datum ensemble
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct DatumEnsembleMember {
    /// The name of the datum.
    pub name: String,
    /// An identifier for the datum.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<Id>,
    /// An array of identifiers for the datum.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub ids: Ids,
}
impl ToProjJSON for DatumEnsembleMember {
    fn set_id(&mut self, id: Id) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if !self.ids.is_empty() {
            self.ids.push(id);
        } else if let Some(i) = self.id.clone() {
            self.ids.extend(vec![i, id]);
            self.id = None;
        } else {
            self.id = Some(id);
        }
    }
}

/// # DatumEnsemble Interface
///
/// Represents a datum ensemble, which is a collection of datums.
///
/// Geodetic and vertical CRSs are associated with either a reference frame (datum) or a datum ensemble. The members of a datum ensemble are given as a list of reference frames. The list may contain reference frame name and/or identifier. All members of a datum ensemble are realizations of one shared terrestrial or vertical reference system.
///
/// For an ensemble of geodetic reference frames (datums), the WKT string includes the description of the ellipsoid used by the members. This information is available from any and all of the definitions of each member. It is included in the ensemble WKT to facilitate direct access to the information. The WKT string for a datum ensemble may also include the description of the prime meridian applying to all members of the ensemble.
///
/// For both geodetic and vertical datum ensembles, the ensemble description includes its 'accuracy', an indication of the difference in coordinate values of a point between different members of the datum ensemble. It may be regarded as a measure of the inaccuracy introduced through the assumption that ensemble members are approximately equivalent.
///
/// Use of the datum ensemble concept comes with a health warning. If data is associated with a CRS having a datum ensemble, it will not be possible to identify which of the datum ensemble members the data might more accurately be referenced to. In high accuracy applications, datum ensembles should not be used; individual reference frames should be identified.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct DatumEnsemble {
    /// Indicates the type of datum ensemble. Always "DatumEnsemble" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'DatumEnsemble';
    /// The name of the datum ensemble.
    pub name: String,
    /// An array of members in the datum ensemble.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub members: Vec<DatumEnsembleMember>,
    /// The accuracy of the datum ensemble.
    pub accuracy: String,
    /// The ellipsoid associated with the datum ensemble.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ellipsoid: Option<Ellipsoid>,
    /// An identifier for the datum ensemble.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<Id>,
    /// An array of identifiers for the datum ensemble.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub ids: Ids,
}
impl ToProjJSON for DatumEnsemble {
    fn set_accuracy(&mut self, accuracy: String) {
        self.accuracy = accuracy;
    }
    fn set_ellipsoid(&mut self, ellipsoid: Ellipsoid) {
        self.ellipsoid = Some(ellipsoid);
    }
    fn set_member(&mut self, member: DatumEnsembleMember) {
        self.members.push(member);
    }
    fn set_id(&mut self, id: Id) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if !self.ids.is_empty() {
            self.ids.push(id);
        } else if let Some(i) = self.id.clone() {
            self.ids.extend(vec![i, id]);
            self.id = None;
        } else {
            self.id = Some(id);
        }
    }
}
impl DatumEnsemble {
    /// Convert a DatumEnsemble to a ProjectionTransform
    pub fn to_projection_transform(&self, proj_transform: &mut ProjectionTransform) {
        if let Some(ellipsoid) = &self.ellipsoid {
            ellipsoid.to_projection_transform(proj_transform);
        }
    }
}

/// # Ellipsoid
///
/// ## Description
/// The `<ellipsoid>` object is an attribute of `<geodetic reference frame>`. It is not used with other types of datum.
///
/// ISO 19111 allows an oblate ellipsoid to be defined through semi-major axis (a) and either
/// semi-minor axis (b) or inverse flattening (1/f). If semi-minor axis is used as the second
/// defining parameter the value for inverse flattening to be shown in the WKT string should be
/// calculated from $1/f  =  a / (a – b)$.
///
/// ISO 19111 also allows for the earth model to be a sphere, for which 1/f is infinite.
/// In this document if the earth model is a sphere `<inverse flattening>` shall be given an
/// artificial value of zero.
///
/// ## Requirements:
/// a) The WKT representation of a sphere shall have an `<inverse flattening>` value of 0.
/// b) `<length unit>` is an optional attribute, optional for reasons of backward compatibility,
/// but it is recommended that it is explicitly included in WKT strings. Its `<conversion factor>`
/// shall be to metres and is the number of metres per unit. `<length unit>` is described in 7.4.
/// If it is omitted then the value for the length of the semi-axis or -axes shall be given in metres.
/// Conversely, if it is omitted then the value for the semi-major axis shall be assumed to be in
/// metres.
///
/// ## Note:
/// - In the WKT for a geodetic, geographic or projected CRS, the length unit for the ellipsoid may
///   differ from the length unit for the coordinate system. The units in which coordinates are expressed
///   are given by the CS element.
/// - In this document the preferred keyword is ELLIPSOID. SPHEROID is permitted for backward compatibility.
///   Implementations should be prepared to read both forms.
///
/// ## Examples of WKT describing an ellipsoid:
/// - `ELLIPSOID["GRS 1980",6378137,298.257222101,LENGTHUNIT["metre",1.0]]`
/// - `SPHEROID["GRS 1980",6378137.0,298.257222101]` (unit = metre is implied)
/// - `ELLIPSOID["Clark 1866",20925832.164,294.97869821, LENGTHUNIT["US survey foot",0.304800609601219]]`
/// - `ELLIPSOID["Sphere",6371000,0,LENGTHUNIT["metre",1.0]]`
///
/// The definition of WKT for a triaxial ellipsoid required for planetary mapping is given in Annex E.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Ellipsoid {
    /// Indicates the type of ellipsoid. Always "Ellipsoid" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'Ellipsoid';
    /// The name of the ellipsoid.
    pub name: String,
    /// The semi-major axis of the ellipsoid.
    /// Represented as a number or a value with a unit.
    pub semi_major_axis: Option<ValueInMetreOrValueAndUnit>,
    /// The semi-minor axis of the ellipsoid.
    /// Represented as a number or a value with a unit.
    /// Required when `inverse_flattening` is not provided.
    pub semi_minor_axis: Option<ValueInMetreOrValueAndUnit>,
    /// The inverse flattening of the ellipsoid.
    /// Required when `semi_minor_axis` is not provided.
    pub inverse_flattening: Option<ValueInMetreOrValueAndUnit>,
    /// The radius of the ellipsoid, used for spherical representations.
    /// Required when neither `semi_minor_axis` nor `inverse_flattening` are provided.
    pub radius: Option<ValueInMetreOrValueAndUnit>,
    /// An identifier for the datum ensemble.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<Id>,
    /// An array of identifiers for the datum ensemble.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub ids: Ids,
}
impl ToProjJSON for Ellipsoid {
    fn set_id(&mut self, id: Id) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if !self.ids.is_empty() {
            self.ids.push(id);
        } else if let Some(i) = self.id.clone() {
            self.ids.extend(vec![i, id]);
            self.id = None;
        } else {
            self.id = Some(id);
        }
    }
}
impl Ellipsoid {
    /// Convert a Ellipsoid to a ProjectionTransform
    pub fn to_projection_transform(&self, proj_transform: &mut ProjectionTransform) {
        let proj = &mut proj_transform.proj.borrow_mut();
        proj.ellps = self.name.clone();
        if let Some(semi_major_axis) = &self.semi_major_axis {
            proj.a = semi_major_axis.meters();
        }
        if let Some(semi_minor_axis) = &self.semi_minor_axis {
            proj.b = semi_minor_axis.meters();
        }
        if let Some(inverse_flattening) = &self.inverse_flattening {
            proj.rf = inverse_flattening.meters();
        }
        if let Some(radius) = &self.radius {
            proj.a = radius.meters();
            proj.b = radius.meters();
            proj.rf = 0.0;
        }
        derive_sphere(proj);
    }
}

/// # Prime meridian
/// The WKT for prime meridian is defined in 8.2.2.
/// In this document the following definition from both ISO 19125-1:2004 and OGC 01-009 has been deprecated but is included here for the purposes of documenting backward compatibility:
/// - `<irm longitude>` is the longitude of the prime meridian measured from the international reference meridian, positive eastward.
/// - `<angle unit>` is an optional attribute, optional for reasons of backward compatibility, but best practice is that it is included in WKT strings. If it is omitted then the value for `<irm longitude>` shall be given in the CRS's `<cs unit>` where this is angular, else in decimal degrees. If the subtype of the geodetic CRS to which the prime meridian is an attribute is geographic, the prime meridian's `<irm longitude>` value shall be given in the same angular units as those for the horizontal axes of the geographic CRS; if the geodetic CRS subtype is geocentric the prime meridian's `<irm longitude>` value shall be given in degrees. Its `<conversion factor>` shall be to radians and is the number of radians per unit. `<angle unit>` is described in 7.4.
///
/// Examples of WKT describing a prime meridian:
/// - `PRIMEM["Paris",2.5969213,ANGLEUNIT["grad",0.015707963267949]]`
/// - `PRIMEM["Greenwich",0.0]`
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct PrimeMeridian {
    /// Indicates the type of prime meridian. Always "PrimeMeridian" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'PrimeMeridian';
    /// The name of the prime meridian.
    pub name: String,
    /// The longitude of the prime meridian.
    /// Represented as a number or a value with a unit.
    pub longitude: ValueInDegreeOrValueAndUnit,
    /// An identifier for the datum ensemble.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<Id>,
    /// An array of identifiers for the datum ensemble.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub ids: Ids,
}
impl PrimeMeridian {
    /// Convert a PrimeMeridian to a ProjectionTransform
    pub fn to_projection_transform(&self, proj_transform: &mut ProjectionTransform) {
        proj_transform.proj.borrow_mut().from_greenwich = self.longitude.rad();
    }
}
impl ToProjJSON for PrimeMeridian {
    fn set_id(&mut self, id: Id) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if !self.ids.is_empty() {
            self.ids.push(id);
        } else if let Some(i) = self.id.clone() {
            self.ids.extend(vec![i, id]);
            self.id = None;
        } else {
            self.id = Some(id);
        }
    }
    fn set_unit(&mut self, unit: Unit) {
        self.longitude.set_unit(unit);
    }
}

/// # ProjectedCRS Interface
///
/// Represents a projected coordinate reference system, which transforms geodetic or geographic
/// coordinates into a flat, two-dimensional plane using a map projection.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct ProjectedCRS {
    /// Indicates the type of CRS. Always "ProjectedCRS" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'ProjectedCRS';
    /// The name of the projected CRS.
    pub name: String,
    /// The base CRS upon which the projection is defined.
    /// Typically a geodetic CRS.
    pub base_crs: GeodeticCRS,
    /// The conversion defining the map projection.
    pub conversion: Conversion,
    /// The coordinate system used in the projected CRS.
    pub coordinate_system: CoordinateSystem,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for ProjectedCRS {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_coordinate_system(&mut self, cs: CoordinateSystem) {
        self.coordinate_system = cs;
    }
    fn set_conversion(&mut self, conversion: Conversion) {
        self.conversion = conversion;
    }
    fn set_geodetic_crs(&mut self, geodetic_crs: GeodeticCRS) {
        self.base_crs = geodetic_crs;
    }
    // Pass down to the coordinate system
    fn set_axis(&mut self, axis: Axis) {
        self.coordinate_system.set_axis(axis);
    }
    fn set_unit(&mut self, unit: Unit) {
        self.coordinate_system.set_unit(unit);
    }
    // NOTE: Conversion also needs variables passed down
    fn set_projection(&mut self, name: String) {
        self.conversion.set_projection(name);
    }
    fn set_method(&mut self, method: Method) {
        self.conversion.set_method(method);
    }
    fn set_parameter(&mut self, parameter: ParameterValue) {
        self.conversion.set_parameter(parameter);
    }
}
impl ProjectedCRS {
    /// Convert a ProjectedCRS to a ProjectionTransform
    pub fn to_projection_transform(&self, proj_transform: &mut ProjectionTransform) {
        // First update the conversion type with "coordinate_system" (set axis step at least)
        self.coordinate_system.to_projection_transform(proj_transform);
        // set base_crs as first step
        self.base_crs.to_projection_transform(proj_transform);
        // set conversion
        self.conversion.to_projection_transform(proj_transform);
    }
}

/// # Conversion Interface
///
/// Represents the map projection or transformation used in a projected CRS.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Conversion {
    /// The schema URL or identifier.
    #[serde(rename = "$schema", skip_serializing_if = "Option::is_none")]
    pub schema: Option<String>,
    /// Indicates the type of conversion. Always "Conversion" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'Conversion';
    /// The name of the conversion (map projection or transformation).
    pub name: String,
    /// The method used for the conversion.
    pub method: Method,
    /// An array of parameter values defining the conversion.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub parameters: Vec<ParameterValue>,
    /// An identifier for the datum ensemble.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<Id>,
    /// An array of identifiers for the datum ensemble.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub ids: Ids,
}
impl ToProjJSON for Conversion {
    fn set_id(&mut self, id: Id) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if !self.ids.is_empty() {
            self.ids.push(id);
        } else if let Some(i) = self.id.clone() {
            self.ids.extend(vec![i, id]);
            self.id = None;
        } else {
            self.id = Some(id);
        }
    }
    fn set_projection(&mut self, name: String) {
        self.method = Method { name, ..Default::default() };
    }
    fn set_method(&mut self, method: Method) {
        self.method = method;
    }
    fn set_parameter(&mut self, parameter: ParameterValue) {
        self.parameters.push(parameter);
    }
}
impl Conversion {
    /// Convert a ProjectedCRS to a ProjectionTransform
    pub fn to_projection_transform(&self, proj_transform: &mut ProjectionTransform) {
        // add Params
        for param in self.parameters.iter() {
            proj_transform.proj.borrow_mut().add_param(param);
        }
        self.method.to_projection_transform(proj_transform);
    }
}

/// # CoordinateMetadata Interface
///
/// Represents metadata associated with a coordinate, including its reference system and epoch.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct CoordinateMetadata {
    /// The schema URL or identifier.
    #[serde(rename = "$schema", skip_serializing_if = "Option::is_none")]
    pub schema: Option<String>,
    /// Indicates the type of object. Always "CoordinateMetadata" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'CoordinateMetadata';
    /// The coordinate reference system associated with the coordinate.
    pub crs: CRS,
    /// The epoch of the coordinate.
    #[serde(rename = "coordinateEpoch", skip_serializing_if = "Option::is_none")]
    pub coordinate_epoch: Option<f64>,
}
impl ToProjJSON for CoordinateMetadata {
    fn set_epoch(&mut self, epoch: f64) {
        self.coordinate_epoch = Some(epoch);
    }
}

/// # Coordinate system type
///
/// For various types of CRS the type of coordinate system that may be used is constrained, as is
/// the permissible number of axes. Additionally the data type for coordinates in an ordinal
/// coordinate system and in a temporal coordinate system is constrained.
///
/// ## Examples of WKT describing an CoordinateSystem with the specified subtype as the first element:
/// - `CS[ordinal,2],AXIS["inline (I)",southeast,ORDER[1]],AXIS["crossline (J)",northeast,ORDER[2]]`
/// - `CS[Cartesian,3],AXIS["(X)",geocentricX],AXIS["(Y)",geocentricY],AXIS["(Z)",geocentricZ],LENGTHUNIT["metre",1.0]`
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
pub enum CoordinateSystemSubtype {
    /// Cartesian
    #[serde(rename = "Cartesian")]
    #[default]
    Cartesian,
    /// Spherical
    #[serde(rename = "spherical")]
    Spherical,
    /// Ellipsoidal
    #[serde(rename = "ellipsoidal")]
    Ellipsoidal,
    /// Vertical
    #[serde(rename = "vertical")]
    Vertical,
    /// Ordinal
    #[serde(rename = "ordinal")]
    Ordinal,
    /// Parametric
    #[serde(rename = "parametric")]
    Parametric,
    /// Affine
    #[serde(rename = "affine")]
    Affine,
    /// TemporalDateTime
    #[serde(rename = "TemporalDateTime")]
    TemporalDateTime,
    /// TemporalCount
    #[serde(rename = "TemporalCount")]
    TemporalCount,
    /// TemporalMeasure
    #[serde(rename = "TemporalMeasure")]
    TemporalMeasure,
}
impl CoordinateSystemSubtype {
    /// Convert a CoordinateSystem to a ProjectionTransform
    pub fn to_projection_transform(&self, _proj_transform: &mut ProjectionTransform) {
        // TODO: ALL of them. I don't know the best way to add cart, but it needs to be a step
        match self {
            CoordinateSystemSubtype::Cartesian => {
                // let cart = CartesianConverter::new(Rc::new(RefCell::new(Proj::default())));
                // proj_transform.cart = Some(Box::new(cart.into()));
            }
            _ => todo!(), /* CoordinateSystemSubtype::Spherical => {}
                           * CoordinateSystemSubtype::Ellipsoidal => {}
                           * CoordinateSystemSubtype::Vertical => {}
                           * CoordinateSystemSubtype::Ordinal => {}
                           * CoordinateSystemSubtype::Parametric => {}
                           * CoordinateSystemSubtype::Affine => {}
                           * CoordinateSystemSubtype::TemporalDateTime => {}
                           * CoordinateSystemSubtype::TemporalCount => {}
                           * CoordinateSystemSubtype::TemporalMeasure => {} */
        }
    }
}

/// # Coordinate System
///
/// Represents a coordinate system, including its subtype and axes.
///
/// Most coordinate system attributes are common to all subtypes of spatial and temporal coordinate systems. Exceptions are associated with the coordinate system axis unit attribute and its qualifier, the conversion factor to an SI base unit:
/// - When the coordinate system type is 'temporalCount' or 'temporalMeasure', the inclusion of the axis unit conversion factor in WKT is conditional, see 7.4.3.
/// - When the coordinate system type is 'ordinal' or 'temporalDateTime', the axis unit attribute and its conversion factor are not required in WKT, see 7.5.6 and 13.3.
///
/// ## Examples of WKT describing an CoordinateSystem:
/// - `CS[ordinal,2],AXIS["inline (I)",southeast,ORDER[1]],AXIS["crossline (J)",northeast,ORDER[2]]`
/// - `CS[Cartesian,3],AXIS["(X)",geocentricX],AXIS["(Y)",geocentricY],AXIS["(Z)",geocentricZ],LENGTHUNIT["metre",1.0]`
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct CoordinateSystem {
    /// The schema URL or identifier.
    #[serde(rename = "$schema", skip_serializing_if = "Option::is_none")]
    pub schema: Option<String>,
    /// Indicates the type of object. Always "CoordinateSystem" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'CoordinateSystem';
    /// The name of the coordinate system.
    pub name: Option<String>,
    /// The subtype of the coordinate system.
    pub subtype: CoordinateSystemSubtype,
    /// The axes of the coordinate system.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub axis: Vec<Axis>,
    /// An identifier for the datum ensemble.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<Id>,
    /// An array of identifiers for the datum ensemble.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub ids: Ids,
}
impl ToProjJSON for CoordinateSystem {
    fn set_id(&mut self, id: Id) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if !self.ids.is_empty() {
            self.ids.push(id);
        } else if let Some(i) = self.id.clone() {
            self.ids.extend(vec![i, id]);
            self.id = None;
        } else {
            self.id = Some(id);
        }
    }
    fn set_axis(&mut self, axis: Axis) {
        self.axis.push(axis);
    }
    fn set_unit(&mut self, unit: Unit) {
        for axis in self.axis.iter_mut() {
            axis.unit = Some(unit.clone());
        }
    }
}
impl CoordinateSystem {
    /// Convert a CoordinateSystem to a ProjectionTransform
    pub fn to_projection_transform(&self, proj_transform: &mut ProjectionTransform) {
        self.subtype.to_projection_transform(proj_transform);
        if !self.axis.is_empty() {
            let mut axiss = self.axis.clone();
            axiss.sort_by(|a, b| a.order.cmp(&b.order));
            let axis: Vec<AxisDirection> = axiss.iter().map(|a| a.direction).collect();
            let mut axis_converter = AxisSwapConverter::new(Rc::new(RefCell::new(Proj::default())));
            axis_converter.swap = axis.into();
            proj_transform.axisswap = Some(Box::new(axis_converter.into()));
        }
    }
}

/// # Transformation Interface
///
/// Represents a transformation between two coordinate reference systems.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct Transformation {
    /// Type identifier
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'Transformation';
    /// Name of the transformation
    pub name: String,
    /// Source CRS
    pub source_crs: CRS,
    /// Target CRS
    pub target_crs: CRS,
    /// Transformation method
    pub method: Method,
    /// Transformation parameters
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub parameters: Vec<ParameterValue>,
    /// Interpolation CRS
    #[serde(skip_serializing_if = "Option::is_none")]
    pub interpolation_crs: Option<CRS>,
    /// Transformation accuracy
    #[serde(skip_serializing_if = "Option::is_none")]
    pub accuracy: Option<String>,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for Transformation {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_accuracy(&mut self, accuracy: String) {
        self.accuracy = Some(accuracy);
    }
    fn set_parameter(&mut self, parameter: ParameterValue) {
        self.parameters.push(parameter);
    }
    fn set_projection(&mut self, name: String) {
        self.method = Method { name, ..Default::default() };
    }
    fn set_method(&mut self, method: Method) {
        self.method = method;
    }
}

/// # TemporalCRS Interface
///
/// Represents a temporal coordinate reference system, which defines time-based coordinates.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct TemporalCRS {
    /// Indicates the type of CRS. Always "TemporalCRS" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'TemporalCRS';
    /// The name of the temporal CRS.
    pub name: String,
    /// The temporal datum associated with the CRS.
    pub datum: TemporalDatum,
    /// The coordinate system used in the temporal CRS.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub coordinate_system: Option<CoordinateSystem>,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for TemporalCRS {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_coordinate_system(&mut self, cs: CoordinateSystem) {
        self.coordinate_system = Some(cs);
    }
    // Pass down to the coordinate system
    fn set_axis(&mut self, axis: Axis) {
        if let Some(ref mut cs) = self.coordinate_system {
            cs.axis.push(axis);
        }
    }
    fn set_unit(&mut self, unit: Unit) {
        if let Some(ref mut cs) = self.coordinate_system {
            for axis in cs.axis.iter_mut() {
                axis.unit = Some(unit.clone());
            }
        }
    }
}

/// # TemporalDatum Interface
///
/// Represents the temporal datum associated with a temporal CRS.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct TemporalDatum {
    /// Indicates the type of datum. Always "TemporalDatum" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'TemporalDatum';
    /// The name of the temporal datum.
    pub name: String,
    /// The calendar system used for the datum.
    pub calendar: String,
    /// The time origin of the temporal datum, typically an ISO 8601 date/time string.
    pub time_origin: Option<String>,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for TemporalDatum {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
}

/// # VerticalCRS Interface
///
/// Represents a vertical coordinate reference system, which is used for height or depth measurements.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct VerticalCRS {
    /// Indicates the type of CRS. Always "VerticalCRS" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'VerticalCRS';
    /// The name of the vertical CRS.
    pub name: String,
    /// The vertical datum associated with the CRS.
    /// One and only one of `datum` or `datum_ensemble` must be provided.
    /// Can only be a `VerticalReferenceFrame` or a `DynamicVerticalReferenceFrame`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub datum: Option<Datum>,
    /// The datum ensemble associated with the CRS.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub datum_ensemble: Option<DatumEnsemble>,
    /// The coordinate system used in the vertical CRS.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub coordinate_system: Option<CoordinateSystem>,
    /// The geoid model associated with the vertical CRS.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub geoid_model: Option<GeoidModel>,
    /// An array of geoid models associated with the vertical CRS.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub geoid_models: Option<Vec<GeoidModel>>,
    /// An array of deformation models associated with the vertical CRS.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub deformation_models: Option<Vec<DeformationModel>>,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for VerticalCRS {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_coordinate_system(&mut self, cs: CoordinateSystem) {
        self.coordinate_system = Some(cs);
    }
    fn set_datum(&mut self, datum: Datum) {
        self.datum = Some(datum);
    }
    fn set_ensemble(&mut self, ensemble: DatumEnsemble) {
        self.datum_ensemble = Some(ensemble);
    }
    // Pass down to the datum
    fn set_prime_meridian(&mut self, prime_meridian: PrimeMeridian) {
        if let Some(ref mut datum) = self.datum {
            datum.set_prime_meridian(prime_meridian);
        }
    }
    // Pass down to the coordinate system
    fn set_axis(&mut self, axis: Axis) {
        if let Some(ref mut cs) = self.coordinate_system {
            cs.axis.push(axis);
        }
    }
    fn set_unit(&mut self, unit: Unit) {
        if let Some(ref mut cs) = self.coordinate_system {
            for axis in cs.axis.iter_mut() {
                axis.unit = Some(unit.clone());
            }
        }
    }
}

/// # VerticalReferenceFrame Interface
///
/// Represents the vertical reference frame associated with a vertical CRS.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct VerticalReferenceFrame {
    /// Indicates the type of reference frame. Always "VerticalReferenceFrame" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'VerticalReferenceFrame';
    /// The name of the vertical reference frame.
    pub name: String,
    /// The anchor point of the reference frame.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub anchor: Option<String>,
    /// The epoch of the anchor point.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub anchor_epoch: Option<f64>,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for VerticalReferenceFrame {
    fn set_anchor(&mut self, anchor: String) {
        self.anchor = Some(anchor);
    }
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_epoch(&mut self, epoch: f64) {
        self.anchor_epoch = Some(epoch);
    }
}

/// # DynamicVerticalReferenceFrame Interface
///
/// Represents a dynamic vertical reference frame.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct DynamicVerticalReferenceFrame {
    /// Indicates the type of reference frame. Always "DynamicVerticalReferenceFrame" for this interface.
    #[serde(rename = "type")]
    pub r#type: Option<String>, // 'DynamicVerticalReferenceFrame';
    /// The name of the reference frame.
    pub name: String,
    /// The anchor point of the reference frame.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub anchor: Option<String>,
    /// The epoch of the anchor point.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub anchor_epoch: Option<f64>,
    /// The frame reference epoch for the dynamic reference frame.
    pub frame_reference_epoch: f64,
    /// Usage Information
    #[serde(flatten, skip_serializing_if = "Option::is_none")]
    pub usage: Option<ObjectUsage>,
    /// Usages
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub usages: Vec<ObjectUsage>,
}
impl ToProjJSON for DynamicVerticalReferenceFrame {
    fn set_id(&mut self, id: Id) {
        if self.usage.is_none() && self.usages.is_empty() {
            self.usage = Some(ObjectUsage::default());
        }
        if let Some(u) = self.usage.as_mut().or_else(|| self.usages.last_mut()) {
            u.set_id(id);
        }
    }
    fn set_usage(&mut self, usage: ObjectUsage) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if self.usages.is_empty() {
            if let Some(u) = self.usage.clone() {
                self.usages.extend(vec![u, usage]);
                self.usage = None;
            } else {
                self.usage = Some(usage);
            }
        } else {
            self.usages.push(usage);
        }
    }
    fn set_anchor(&mut self, anchor: String) {
        self.anchor = Some(anchor);
    }
    fn set_epoch(&mut self, epoch: f64) {
        self.anchor_epoch = Some(epoch);
    }
    fn set_frame_epoch(&mut self, epoch: f64) {
        self.frame_reference_epoch = epoch;
    }
}

/// # GeoidModel Interface
///
/// Represents a geoid model associated with a vertical CRS.
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct GeoidModel {
    /// The name of the geoid model.
    pub name: String,
    /// The interpolation CRS for the geoid model.
    pub interpolation_crs: Option<Box<CRS>>,
    /// An identifier for the geoid model.
    pub id: Option<Id>,
}

/// # Usage
///
/// ## Description
/// Usage is an optional attribute which if included in a WKT string shall include both
/// `<scope>` and `<extent>`. Multiple pairs of scope/extent may be used to describe the usage for
/// different purposes over different extents. In this document the `<scope>` and `<extent>` elements
/// may not be given alone but only as a pairing. Within each pairing, extent may consist of one or
/// more of area textual description, area bounding box, vertical extent and/or temporal extent,
/// see 7.3.2.3.
///
/// ## Examples
/// - `USAGE[<scope>,<extent>]`
/// - `USAGE[scope1,extent1],USAGE[scope2,extent2]`
#[derive(Debug, Default, Clone, Serialize, Deserialize, PartialEq)]
#[serde(default)]
pub struct ObjectUsage {
    /// The schema URL or identifier.
    #[serde(rename = "$schema", skip_serializing_if = "Option::is_none")]
    pub schema: Option<String>,
    /// The scope of the CRS.
    #[serde(skip_serializing_if = "String::is_empty")]
    pub scope: String,
    /// The extent if applicable.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub area: Option<String>,
    /// bbox
    #[serde(skip_serializing_if = "Option::is_none")]
    pub bbox: Option<ProjBBox>,
    /// vertical_extent
    #[serde(skip_serializing_if = "Option::is_none")]
    pub vertical_extent: Option<VerticalExtent>,
    /// temporal_extent
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temporal_extent: Option<TemporalExtent>,
    /// Remarks or additional information about the CRS.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub remarks: Option<String>,
    /// An identifier for the CRS.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<Id>,
    /// An array of identifiers for the CRS.
    #[serde(skip_serializing_if = "Vec::is_empty")]
    pub ids: Ids,
}
impl ToProjJSON for ObjectUsage {
    fn set_id(&mut self, id: Id) {
        // If array is active, add to array; if id is already set, migrate to array; otherwise set id
        if !self.ids.is_empty() {
            self.ids.push(id);
        } else if let Some(i) = self.id.clone() {
            self.ids.extend(vec![i, id]);
            self.id = None;
        } else {
            self.id = Some(id);
        }
    }
    fn set_temporal_extent(&mut self, extent: TemporalExtent) {
        self.temporal_extent = Some(extent);
    }
    fn set_vertical_extent(&mut self, extent: VerticalExtent) {
        self.vertical_extent = Some(extent);
    }
    fn set_bbox(&mut self, bbox: ProjBBox) {
        self.bbox = Some(bbox);
    }
    fn set_area(&mut self, area: Option<String>) {
        self.area = area;
    }
}