msoffice_pptx 0.2.1

pptx file format deserializer
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
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
use msoffice_shared::error::{MissingAttributeError, MissingChildNodeError, NotGroupMemberError};
use msoffice_shared::xml::{parse_xml_bool, XmlNode};
use std::str::FromStr;

use enum_from_str::ParseEnumVariantError;
use enum_from_str_derive::FromStr;

pub type Result<T> = ::std::result::Result<T, Box<dyn (::std::error::Error)>>;

/// This simple type defines the position of an object in an ordered list.
pub type Index = u32;
/// This simple type represents a node or event on the timeline by its identifier.
pub type TLTimeNodeId = u32;
pub type TLSubShapeId = msoffice_shared::drawingml::ShapeId;

/// This simple type defines an animation target element that is represented by a subelement of a chart.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLChartSubelementType {
    #[from_str = "gridLegend"]
    GridLegend,
    #[from_str = "series"]
    Series,
    #[from_str = "category"]
    Category,
    #[from_str = "ptInSeries"]
    PointInSeries,
    #[from_str = "ptInCategory"]
    PointInCategory,
}

/// This simple type describes how to build a paragraph.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLParaBuildType {
    /// Specifies to animate all paragraphs at once.
    #[from_str = "allAtOnce"]
    AllAtOnce,
    /// Specifies to animate paragraphs grouped by bullet level.
    #[from_str = "p"]
    Paragraph,
    /// Specifies the build has custom user settings.
    #[from_str = "cust"]
    Custom,
    /// Specifies to animate the entire body of text as one block.
    #[from_str = "whole"]
    Whole,
}

/// This simple type specifies the different diagram build types.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLDiagramBuildType {
    #[from_str = "whole"]
    Whole,
    #[from_str = "depthByNode"]
    DepthByNode,
    #[from_str = "depthByBranch"]
    DepthByBranch,
    #[from_str = "breadthByNode"]
    BreadthByNode,
    #[from_str = "breadthByLvl"]
    BreadthByLevel,
    #[from_str = "cw"]
    Clockwise,
    #[from_str = "cwIn"]
    ClockwiseIn,
    #[from_str = "cwOut"]
    ClockwiseOut,
    #[from_str = "ccw"]
    CounterClockwise,
    #[from_str = "ccwIn"]
    CounterClockwiseIn,
    #[from_str = "ccwOut"]
    CounterClockwiseOut,
    #[from_str = "inByRing"]
    InByRing,
    #[from_str = "outByRing"]
    OutByRing,
    #[from_str = "up"]
    Up,
    #[from_str = "down"]
    Down,
    #[from_str = "allAtOnce"]
    AllAtOnce,
    #[from_str = "cust"]
    Custom,
}

/// This simple type describes how to build an embedded Chart.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLOleChartBuildType {
    #[from_str = "allAtOnce"]
    AllAtOnce,
    #[from_str = "series"]
    Series,
    #[from_str = "category"]
    Category,
    #[from_str = "seriesEl"]
    SeriesElement,
    #[from_str = "categoryEl"]
    CategoryElement,
}

/// This simple type specifies the child time node that triggers a time condition. References a child TimeNode or all
/// child nodes. Order is based on the child's end time.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLTriggerRuntimeNode {
    #[from_str = "first"]
    First,
    #[from_str = "last"]
    Last,
    #[from_str = "all"]
    All,
}

/// This simple type specifies a particular event that causes the time condition to be true.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLTriggerEvent {
    /// Fire trigger at the beginning
    #[from_str = "onBegin"]
    OnBegin,
    /// Fire trigger at the end
    #[from_str = "onEnd"]
    OnEnd,
    /// Fire trigger at the beginning
    #[from_str = "begin"]
    Begin,
    /// Fire trigger at the end
    #[from_str = "end"]
    End,
    /// Fire trigger on a mouse click
    #[from_str = "onClick"]
    OnClick,
    /// Fire trigger on double-mouse click
    #[from_str = "onDblClick"]
    OnDoubleClick,
    /// Fire trigger on mouse over
    #[from_str = "onMouseOver"]
    OnMouseOver,
    /// Fire trigger on mouse out
    #[from_str = "onMouseOut"]
    OnMouseOut,
    /// Fire trigger on next node
    #[from_str = "onNext"]
    OnNext,
    /// Fire trigger on previous node
    #[from_str = "onPrev"]
    OnPrev,
    /// Fire trigger on stop audio
    #[from_str = "onStopAudio"]
    OnStopAudio,
}

/// This simple type specifies how the animation is applied over subelements of the target element.
#[derive(Debug, Copy, Clone, PartialEq, FromStr)]
pub enum IterateType {
    /// Iterate by element.
    #[from_str = "el"]
    Element,
    /// Iterate by Letter.
    #[from_str = "wd"]
    Word,
    /// Iterate by Word.
    #[from_str = "lt"]
    Letter,
}

/// This simple type specifies the class of effect in which this effect belongs.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLTimeNodePresetClassType {
    #[from_str = "entr"]
    Entrance,
    #[from_str = "exit"]
    Exit,
    #[from_str = "emph"]
    Emphasis,
    #[from_str = "path"]
    Path,
    #[from_str = "verb"]
    Verb,
    #[from_str = "mediacall"]
    Mediacall,
}

/// This simple type determines whether an effect can play more than once.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLTimeNodeRestartType {
    /// Always restart node
    #[from_str = "always"]
    Always,
    /// Restart when node is not active
    #[from_str = "whenNotActive"]
    WhenNotActive,
    /// Never restart node
    #[from_str = "never"]
    Never,
}

/// This simple type specifies what modifications the effect leaves on the target element's properties when the
/// effect ends.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLTimeNodeFillType {
    #[from_str = "remove"]
    Remove,
    #[from_str = "freeze"]
    Freeze,
    #[from_str = "hold"]
    Hold,
    #[from_str = "transition"]
    Transition,
}

/// This simple type specifies how the time node synchronizes to its group.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLTimeNodeSyncType {
    #[from_str = "canSlip"]
    CanSlip,
    #[from_str = "locked"]
    Locked,
}

/// This simple type specifies how the time node plays back relative to its master time node.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLTimeNodeMasterRelation {
    #[from_str = "sameClick"]
    SameClick,
    #[from_str = "lastClick"]
    LastClick,
    #[from_str = "nextClick"]
    NextClick,
}

/// This simple type specifies time node types.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLTimeNodeType {
    #[from_str = "clickEffect"]
    ClickEffect,
    #[from_str = "withEffect"]
    WithEffect,
    #[from_str = "afterEffect"]
    AfterEffect,
    #[from_str = "mainSequence"]
    MainSequence,
    #[from_str = "interactiveSeq"]
    InteractiveSequence,
    #[from_str = "clickPar"]
    ClickParagraph,
    #[from_str = "withGroup"]
    WithGroup,
    #[from_str = "afterGroup"]
    AfterGroup,
    #[from_str = "tmRoot"]
    TimingRoot,
}

/// This simple type specifies what to do when going forward in a sequence. When the value is Seek, it seeks the
/// current child element to its natural end time before advancing to the next element.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLNextActionType {
    #[from_str = "none"]
    None,
    #[from_str = "seek"]
    Seek,
}

/// This simple type specifies what to do when going backwards in a sequence. When the value is SkipTimed, the
/// sequence continues to go backwards until it reaches a sequence element that was defined to being only on a
/// "next" event.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLPreviousActionType {
    #[from_str = "none"]
    None,
    #[from_str = "skipTimed"]
    SkipTimed,
}

/// This simple type specifies how the animation flows from point to point.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLAnimateBehaviorCalcMode {
    #[from_str = "discrete"]
    Discrete,
    #[from_str = "fmla"]
    Formula,
    #[from_str = "lin"]
    Linear,
}

/// This simple type specifies the type of property value.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLAnimateBehaviorValueType {
    #[from_str = "clr"]
    Color,
    #[from_str = "num"]
    Number,
    #[from_str = "str"]
    String,
}

/// This simple type specifies how to apply the animation values to the original value for the property.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLBehaviorAdditiveType {
    #[from_str = "base"]
    Base,
    #[from_str = "sum"]
    Sum,
    #[from_str = "repl"]
    Replace,
    #[from_str = "mult"]
    Multiply,
    #[from_str = "none"]
    None,
}

/// This simple type makes a repeating animation build with each iteration when set to "always."
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLBehaviorAccumulateType {
    #[from_str = "none"]
    None,
    #[from_str = "always"]
    Always,
}

/// This simple type specifies how the behavior animates the target element.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLBehaviorTransformType {
    #[from_str = "pt"]
    Point,
    #[from_str = "img"]
    Image,
}

/// This simple type specifies how a behavior should override values of the attribute being animated on the target
/// element. The ChildStyle clears the attributes on the children contained inside the target element.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLBehaviorOverrideType {
    #[from_str = "normal"]
    Normal,
    #[from_str = "childStyle"]
    ChildStyle,
}

/// This simple type specifies the color space of the animation.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLAnimateColorSpace {
    #[from_str = "rgb"]
    Rgb,
    #[from_str = "hsl"]
    Hsl,
}

/// This simple type specifies the direction in which to interpolate the animation (clockwise or counterclockwise).
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLAnimateColorDirection {
    #[from_str = "cw"]
    Clockwise,
    #[from_str = "ccw"]
    CounterClockwise,
}

/// This simple type specifies whether the effect is a transition in, transition out, or neither.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLAnimateEffectTransition {
    #[from_str = "in"]
    In,
    #[from_str = "out"]
    Out,
    #[from_str = "none"]
    None,
}

/// This simple type specifies what the origin of the motion path is relative to.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLAnimateMotionBehaviorOrigin {
    #[from_str = "parent"]
    Parent,
    #[from_str = "layout"]
    Layout,
}

/// This simple type specifies how the motion path moves when the target element is moved.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLAnimateMotionPathEditMode {
    #[from_str = "relative"]
    Relative,
    #[from_str = "fixed"]
    Fixed,
}

/// This simple type specifies a command type.
#[derive(Debug, Clone, Copy, PartialEq, FromStr)]
pub enum TLCommandType {
    #[from_str = "evt"]
    Event,
    #[from_str = "call"]
    Call,
    #[from_str = "verb"]
    Verb,
}

#[derive(Debug, Clone)]
pub struct IndexRange {
    /// This attribute defines the start of the index range.
    pub start: Index,
    /// This attribute defines the end of the index range.
    pub end: Index,
}

impl IndexRange {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut start = None;
        let mut end = None;

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "st" => start = Some(value.parse()?),
                "end" => end = Some(value.parse()?),
                _ => (),
            }
        }

        let start = start.ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "st"))?;
        let end = end.ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "end"))?;

        Ok(Self { start, end })
    }
}

#[derive(Debug, Clone)]
pub enum TimeNodeGroup {
    /// This element describes the Parallel time node which can be activated along with other parallel time node
    /// containers.
    ///
    /// # Xml example
    ///
    /// ```xml
    /// <p:timing>
    ///   <p:tnLst>
    ///     <p:par>
    ///       <p:cTn id="1" dur="indefinite" restart="never" nodeType="tmRoot">
    ///         <p:childTnLst>
    ///           <p:seq concurrent="1" nextAc="seek">
    ///    ///           </p:seq>
    ///         </p:childTnLst>
    ///       </p:cTn>
    ///     </p:par>
    ///   </p:tnLst>
    /// </p:timing>
    /// ```
    Parallel(Box<TLCommonTimeNodeData>),
    /// This element describes the Sequence time node and it can only be activated when the one before it finishes.
    ///
    /// # Xml example
    ///
    /// For example, suppose we have a simple animation with a blind entrance.
    /// ```xml
    /// <p:timing>
    ///   <p:tnLst>
    ///     <p:par>
    ///       <p:cTn id="1" dur="indefinite" restart="never" nodeType="tmRoot">
    ///         <p:childTnLst>
    ///           <p:seq concurrent="1" nextAc="seek">
    ///    ///           </p:seq>
    ///         </p:childTnLst>
    ///       </p:cTn>
    ///     </p:par>
    ///   </p:tnLst>
    /// </p:timing>
    /// ```
    Sequence(Box<TLTimeNodeSequence>),
    /// This element describes the Exclusive time node. This time node is used to pause all other timelines when it is
    /// activated.
    Exclusive(Box<TLCommonTimeNodeData>),
    /// This element is a generic animation element that requires little or no semantic understanding of the attribute
    /// being animated. It can animate text within a shape or even the shape itself.
    ///
    /// # Xml example
    ///
    /// Consider trying to emphasize text within a shape by changing the size of its font by 150%. The
    /// <anim> element should be used as follows:
    ///
    /// ```xml
    /// <p:anim to="1.5" calcmode="lin" valueType="num">
    ///   <p:cBhvr override="childStyle">
    ///     <p:cTn id="1" dur="2000" fill="hold"/>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="1">
    ///         <p:txEl>
    ///           <p:charRg st="1" end="4"/>
    ///         </p:txEl>
    ///       </p:spTgt>
    ///     </p:tgtEl>
    ///     <p:attrNameLst>
    ///       <p:attrName>style.fontSize</p:attrName>
    ///     </p:attrNameLst>
    ///   </p:cBhvr>
    /// </p:anim>
    /// ```
    Animate(Box<TLAnimateBehavior>),
    /// This animation element is responsible for animating the color of an object.
    ///
    /// # Xml example
    ///
    /// Consider trying to emphasize a shape by changing its fill color to scheme color accent2. The
    /// <animClr> element should be used as follows:
    /// ```xml
    /// <p:animClr clrSpc="rgb">
    ///   <p:cBhvr>
    ///     <p:cTn id="1" dur="2000" fill="hold"/>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="1"/>
    ///     </p:tgtEl>
    ///     <p:attrNameLst>
    ///       <p:attrName>fillcolor</p:attrName>
    ///     </p:attrNameLst>
    ///   </p:cBhvr>
    ///   <p:to>
    ///     <a:schemeClr val="accent2"/>
    ///   </p:to>
    /// </p:animClr>
    /// ```
    AnimateColor(Box<TLAnimateColorBehavior>),
    /// This animation behavior provides the ability to do image transform/filter effects on elements. Some visual
    /// effects are dynamic in nature and have a progress that animates from 0 to 1 over a period of time to do visual
    /// transitions between hidden and visible states. Other filters are static and apply a effects like a blur or drop-
    /// shadow which aren't inherently time-based.
    ///
    /// # Xml example
    ///
    /// Consider trying to emphasize a shape by creating an entrance animation using a "blinds" motion.
    /// ```xml
    /// <p:animEffect transition="in" filter="blinds(horizontal)">
    ///   <p:cBhvr>
    ///     <p:cTn id="7" dur="500"/>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="4"/>
    ///     </p:tgtEl>
    ///   </p:cBhvr>
    /// </p:animEffect>
    /// ```
    AnimateEffect(Box<TLAnimateEffectBehavior>),
    /// Animate motion provides an abstracted way to move positioned elements. It provides the ability to specify
    /// from/to/by motion as well as to use more detailed path descriptions for motion over polylines or bezier curves.
    ///
    /// # Xml example
    ///
    /// Consider animating a shape from its original position to the right.. The <animMotion> element should
    /// be used as follows:
    ///
    /// ```xml
    /// <p:animMotion origin="layout" path="M 0 0 L 0.25 0 E" pathEditMode="relative">
    ///   <p:cBhvr>
    ///     <p:cTn id="1" dur="2000" fill="hold"/>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="1"/>
    ///     </p:tgtEl>
    ///     <p:attrNameLst>
    ///       <p:attrName>ppt_x</p:attrName>
    ///       <p:attrName>ppt_y</p:attrName>
    ///     </p:attrNameLst>
    ///   </p:cBhvr>
    /// </p:animMotion>
    /// ```
    AnimateMotion(Box<TLAnimateMotionBehavior>),
    /// This animation element is responsible for animating the rotation of an object. Rotation values set in the "by",
    /// "to, and "from" attributes are specified in degrees measured to a 60,000th, i.e 1 degree is 60,000. Rotation
    /// values can be larger than 360°.
    ///
    /// The sign of the rotation angle specifies the direction for rotation. A negative rotation specifies that the rotation
    /// should appear in the host to go counter-clockwise".
    ///
    /// # Xml example
    ///
    /// Consider trying to emphasize a shape by rotating it 360 degrees clockwise. The <animRot> element
    /// should be used as follows:
    ///
    /// ```xml
    /// <p:animRot by="21600000">
    ///   <p:cBhvr>
    ///     <p:cTn id="6" dur="2000" fill="hold"/>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="5"/>
    ///     </p:tgtEl>
    ///     <p:attrNameLst>
    ///       <p:attrName>r</p:attrName>
    ///     </p:attrNameLst>
    ///   </p:cBhvr>
    /// </p:animRot>
    /// ```
    AnimateRotation(Box<TLAnimateRotationBehavior>),
    /// This animation element is responsible for animating the scale of an object. When animating the scale, the
    /// element shall scale around the reference point of the element and the positioning system used should be
    /// consistent with the one used for motion paths. When animating the width and height of an element, all of the
    /// width/height animation values are calculated first then the scale animations are applied on top of that. So for
    /// example, an animation from 0 to 100 of the width with a concurrent scale from 100% to 200% would result in
    /// the element appearing to scale from 0 to 200.
    ///
    /// # Xml example
    ///
    /// Consider trying to emphasize a shape by scaling it larger by 150%. The <animScale> element should
    /// be used as follows:
    ///
    /// ```xml
    /// <p:childTnLst>
    ///   <p:animScale>
    ///     <p:cBhvr>
    ///       <p:cTn id="6" dur="2000" fill="hold"/>
    ///       <p:tgtEl>
    ///         <p:spTgt spid="5"/>
    ///       </p:tgtEl>
    ///     </p:cBhvr>
    ///     <p:by x="150000" y="150000"/>
    ///   </p:animScale>
    /// </p:childTnLst>
    /// ```
    AnimateScale(Box<TLAnimateScaleBehavior>),
    /// This element describes the several non-durational commands that can be executed within a timeline. This can
    /// be used to send events, call functions on elements, and send verbs to embedded objects. For example “Object
    /// Action” effects for Embedded objects and Media commands for sounds/movies such as "PlayFrom(0.0)" and
    /// "togglePause".
    Command(Box<TLCommandBehavior>),
    /// This element allows the setting of a particular property value to a fixed value while the behavior is active and
    /// restores the value when the behavior is reset or turned off.
    ///
    /// # Xml example
    ///
    /// For example, suppose we want to set certain properties during an animation effect. The <set>
    /// element should be used as follows:
    /// ```xml
    /// <p:childTnLst>
    ///   <p:set>
    ///     <p:cBhvr>
    ///       <p:cTn id="6" dur="1" fill="hold"> … </p:cTn>
    ///       <p:tgtEl>
    ///         <p:spTgt spid="4"/>
    ///       </p:tgtEl>
    ///       <p:attrNameLst>
    ///         <p:attrName>style.visibility</p:attrName>
    ///       </p:attrNameLst>
    ///     </p:cBhvr>
    ///     <p:to>
    ///       <p:strVal val="visible"/>
    ///     </p:to>
    ///   </p:set>
    ///   <p:animEffect transition="in" filter="blinds(horizontal)">
    ///    ///   </p:animEffect>
    /// </p:childTnLst>
    /// ```
    Set(Box<TLSetBehavior>),
    /// This element is used to include audio during an animation. This element specifies that this node within the
    /// animation tree triggers the playback of an audio file; the actual audio file used is specified by the sndTgt
    /// element (§19.5.70).
    ///
    /// # Xml example
    ///
    /// Consider adding applause sound to an animation sequence. The audio element is used as follows:
    ///
    /// ```xml
    /// <p:cTn ...>
    ///   <p:stCondLst>...</p:stCondLst>
    ///   <p:childTnLst>...</p:childTnLst>
    ///   <p:subTnLst>
    ///     <p:audio>
    ///       <p:cMediaNode vol="50%">...
    ///         <p:tgtEl>
    ///           <p:sndTgt r:embed="rId2" />
    ///         </p:tgtEl>
    ///       </p:cMediaNode>
    ///     </p:audio>
    ///   </p:subTnLst>
    /// </p:cTn>
    /// ```
    ///
    /// The audio element specifies the location of the audio playback within the animation; its child sndTgt element
    /// specifies that the audio to be played is the target of the relationship with ID rId2.
    Audio(Box<TLMediaNodeAudio>),
    /// This element specifies video information in an animation sequence. This element specifies that this node within
    /// the animation tree triggers the playback of a video file; the actual video file used is specified by the videoFile
    /// element
    ///
    /// # Xml example
    ///
    /// Consider a slide with an animated video content. The <video> element is used as follows:
    /// ```xml
    /// <p:cSld>
    ///   <p:spTree>
    ///     <p:pic>
    ///       <p:nvPicPr>
    ///       <p:cNvPr id="4"/>
    ///    ///       <p:nvPr>
    ///         <a:videoFile r:link="rId1" contentType="video/ogg"/>
    ///       </p:nvPr>
    ///     </p:nvPicPr>
    ///    ///     </p:pic>
    ///   </p:spTree>
    /// </p:cSld>
    ///    /// <p:childTnLst>
    ///   <p:seq concurrent="1" nextAc="seek">
    ///    ///   </p:seq>
    ///   <p:video>
    ///     <p:cMediaNode>
    ///    ///       <p:tgtEl>
    ///         <p:spTgt spid="4"/>
    ///       </p:tgtEl>
    ///     </p:cMediaNode>
    ///   </p:video>
    /// </p:childTnLst>
    /// ```
    ///
    /// The video element specifies the location of the video playback within the animation sequence; its child spTgt
    /// element specifies that the shape which contains the video to be played has a shape ID of 4. If we look at the
    /// shape with that ID value, its child videoFile element references an external video file of content type video/ogg
    /// located at the target of the relationship with ID rId1
    Video(Box<TLMediaNodeVideo>),
}

impl TimeNodeGroup {
    pub fn is_choice_member<T>(name: T) -> bool
    where
        T: AsRef<str>,
    {
        match name.as_ref() {
            "par" | "seq" | "excl" | "anim" | "animClr" | "animEffect" | "animMotion" | "animRot" | "animScale"
            | "cmd" | "set" | "audio" | "video" => true,
            _ => false,
        }
    }

    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        match xml_node.local_name() {
            "par" => Ok(TimeNodeGroup::Parallel(Box::new(
                TLCommonTimeNodeData::from_xml_element(xml_node)?,
            ))),
            "seq" => Ok(TimeNodeGroup::Sequence(Box::new(TLTimeNodeSequence::from_xml_element(
                xml_node,
            )?))),
            "excl" => Ok(TimeNodeGroup::Exclusive(Box::new(
                TLCommonTimeNodeData::from_xml_element(xml_node)?,
            ))),
            "anim" => Ok(TimeNodeGroup::Animate(Box::new(TLAnimateBehavior::from_xml_element(
                xml_node,
            )?))),
            "animClr" => Ok(TimeNodeGroup::AnimateColor(Box::new(
                TLAnimateColorBehavior::from_xml_element(xml_node)?,
            ))),
            "animEffect" => Ok(TimeNodeGroup::AnimateEffect(Box::new(
                TLAnimateEffectBehavior::from_xml_element(xml_node)?,
            ))),
            "animMotion" => Ok(TimeNodeGroup::AnimateMotion(Box::new(
                TLAnimateMotionBehavior::from_xml_element(xml_node)?,
            ))),
            "animRot" => Ok(TimeNodeGroup::AnimateRotation(Box::new(
                TLAnimateRotationBehavior::from_xml_element(xml_node)?,
            ))),
            "animScale" => Ok(TimeNodeGroup::AnimateScale(Box::new(
                TLAnimateScaleBehavior::from_xml_element(xml_node)?,
            ))),
            "cmd" => Ok(TimeNodeGroup::Command(Box::new(TLCommandBehavior::from_xml_element(
                xml_node,
            )?))),
            "set" => Ok(TimeNodeGroup::Set(Box::new(TLSetBehavior::from_xml_element(xml_node)?))),
            "audio" => Ok(TimeNodeGroup::Audio(Box::new(TLMediaNodeAudio::from_xml_element(
                xml_node,
            )?))),
            "video" => Ok(TimeNodeGroup::Video(Box::new(TLMediaNodeVideo::from_xml_element(
                xml_node,
            )?))),
            _ => Err(Box::new(NotGroupMemberError::new(
                xml_node.name.clone(),
                "TimeNodeGroup",
            ))),
        }
    }
}

/// This element describes the common behaviors of animations.
///
/// # Xml example
///
/// ```xml
/// <p:anim to="1.5" calcmode="lin" valueType="num">
///   <p:cBhvr override="childStyle">
///     <p:cTn id="6" dur="2000" fill="hold"/>
///     <p:tgtEl>
///       <p:spTgt spid="3">
///         <p:txEl>
///           <p:charRg st="4294967295" end="4294967295"/>
///         </p:txEl>
///       </p:spTgt>
///     </p:tgtEl>
///     <p:attrNameLst>
///       <p:attrName>style.fontSize</p:attrName>
///     </p:attrNameLst>
///   </p:cBhvr>
/// </p:anim>
/// ```
#[derive(Debug, Clone)]
pub struct TLCommonBehaviorData {
    pub additive: Option<TLBehaviorAdditiveType>,
    pub accumulate: Option<TLBehaviorAccumulateType>,
    pub transform_type: Option<TLBehaviorTransformType>,
    pub from: Option<String>,
    pub to: Option<String>,
    pub by: Option<String>,
    pub runtime_context: Option<String>,
    pub override_type: Option<TLBehaviorOverrideType>,
    pub common_time_node_data: Box<TLCommonTimeNodeData>,
    /// This element specifies the target children elements which have the animation effects applied to.
    ///
    /// # Xml example
    ///
    /// Consider a shape with ID 3 with a fade effect animation applied to it. The <tgtEl> element should be
    /// used as follows:
    /// ```xml
    /// <p:animEffect transition="in" filter="fade">
    ///   <p:cBhvr>
    ///     <p:cTn id="7" dur="2000"/>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="3"/>
    ///     </p:tgtEl>
    ///   </p:cBhvr>
    /// </p:animEffect>
    /// ```
    pub target_element: TLTimeTargetElement,
    /// This element is used to describe a list of attributes in which to apply an animation to.
    ///
    /// The elements of this list is used to contain an attribute value for an Attribute Name List. This value defines the specific
    /// attribute that an animation should be applied to, such as fill, style, and shadow, etc. A specific property is
    /// defined by using a "property.sub-property" format which is often extended to multiple sub properties as seen in
    /// the allowed values below.
    ///
    /// Allowed property values:
    /// * style.opacity
    /// * style.rotation
    /// * style.visibility
    /// * style.color
    /// * style.fontSize
    /// * style.fontWeight
    /// * style.fontStyle
    /// * style.fontFamily
    /// * style.textEffectEmboss
    /// * style.textShadow
    /// * style.textTransform
    /// * style.textDecorationUnderline
    /// * style.textEffectOutline
    /// * style.textDecorationLineThrough
    /// * style.sRotation
    /// * imageData.cropTop
    /// * imageData.cropBottom
    /// * imageData.cropLeft
    /// * imageData.cropRight
    /// * imageData.gain
    /// * imageData.blacklevel
    /// * imageData.gamma
    /// * imageData.grayscale
    /// * imageData.chromakey
    /// * fill.on
    /// * fill.type
    /// * fill.color
    /// * fill.opacity
    /// * fill.color2
    /// * fill.method
    /// * fill.opacity2
    /// * fill.angle
    /// * fill.focus
    /// * fill.focusposition.x
    /// * fill.focusposition.y
    /// * fill.focussize.x
    /// * fill.focussize.y
    /// * stroke.on
    /// * stroke.color
    /// * stroke.weight
    /// * stroke.opacity
    /// * stroke.linestyle
    /// * stroke.dashstyle
    /// * stroke.filltype
    /// * stroke.src
    /// * stroke.color2
    /// * stroke.imagesize.x
    /// * stroke.imagesize.y
    /// * stroke.startArrow
    /// * stroke.endArrow
    /// * stroke.startArrowWidth
    /// * stroke.startArrowLength
    /// * stroke.endArrowWidth
    /// * stroke.endArrowLength
    /// * shadow.on
    /// * shadow.type
    /// * shadow.color
    /// * shadow.color2
    /// * shadow.opacity
    /// * shadow.offset.x
    /// * shadow.offset.y
    /// * shadow.offset2.x
    /// * shadow.offset2.y
    /// * shadow.origin.x
    /// * shadow.origin.y
    /// * shadow.matrix.xtox
    /// * shadow.matrix.ytox
    /// * shadow.matrix.xtoy
    /// * shadow.matrix.ytoy
    /// * shadow.matrix.perspectiveX
    /// * shadow.matrix.perspectiveY
    /// * skew.on
    /// * skew.offset.x
    /// * skew.offset.y
    /// * skew.origin.x
    /// * skew.origin.y
    /// * skew.matrix.xtox
    /// * skew.matrix.ytox
    /// * skew.matrix.xtoy
    /// * skew.matrix.ytoy
    /// * skew.matrix.perspectiveX
    /// * skew.matrix.perspectiveY
    /// * extrusion.on
    /// * extrusion.type
    /// * extrusion.render
    /// * extrusion.viewpointorigin.x
    /// * extrusion.viewpointorigin.y
    /// * extrusion.viewpoint.x
    /// * extrusion.viewpoint.y
    /// * extrusion.viewpoint.z
    /// * extrusion.plane
    /// * extrusion.skewangle
    /// * extrusion.skewamt
    /// * extrusion.backdepth,
    /// * extrusion.foredepth
    /// * extrusion.orientation.x
    /// * extrusion.orientation.y
    /// * extrusion.orientation.zand
    /// * extrusion.orientationangle
    /// * extrusion.color,
    /// * extrusion.rotationangle.x
    /// * extrusion.rotationangle.y
    /// * extrusion.lockrotationcenter
    /// * extrusion.autorotationcenter
    /// * extrusion.rotationcenter.x
    /// * extrusion.rotationcenter.y
    /// * extrusion.rotationcenter.z
    /// * extrusion.colormode.
    ///
    /// # Xml example
    ///
    /// Consider trying to emphasize the txt font size within the body of a shape. The attribute would be
    /// 'style.fontSize' and this can be done by doing the following:
    ///
    /// ```xml
    /// <p:anim to="1.5" calcmode="lin" valueType="num">
    ///   <p:cBhvr override="childStyle">
    ///     <p:cTn id="6" dur="2000" fill="hold"/>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="3">
    ///         <p:txEl>
    ///           <p:charRg st="4294967295" end="4294967295"/>
    ///         </p:txEl>
    ///       </p:spTgt>
    ///     </p:tgtEl>
    ///     <p:attrNameLst>
    ///       <p:attrName>style.fontSize</p:attrName>
    ///     </p:attrNameLst>
    ///   </p:cBhvr>
    /// </p:anim>
    /// ```
    pub attr_name_list: Option<Vec<String>>,
}

impl TLCommonBehaviorData {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut additive = None;
        let mut accumulate = None;
        let mut transform_type = None;
        let mut from = None;
        let mut to = None;
        let mut by = None;
        let mut runtime_context = None;
        let mut override_type = None;

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "additive" => additive = Some(value.parse()?),
                "accumulate" => accumulate = Some(value.parse()?),
                "xfrmType" => transform_type = Some(value.parse()?),
                "from" => from = Some(value.clone()),
                "to" => to = Some(value.clone()),
                "by" => by = Some(value.clone()),
                "rctx" => runtime_context = Some(value.clone()),
                "override" => override_type = Some(value.parse()?),
                _ => (),
            }
        }

        let mut common_time_node_data = None;
        let mut target_element = None;
        let mut attr_name_list = None;

        for child_node in &xml_node.child_nodes {
            match child_node.local_name() {
                "cTn" => common_time_node_data = Some(Box::new(TLCommonTimeNodeData::from_xml_element(child_node)?)),
                "tgtEl" => target_element = Some(TLTimeTargetElement::from_xml_element(child_node)?),
                "attrNameLst" => {
                    let mut vec = Vec::new();
                    for attr_name_node in &child_node.child_nodes {
                        vec.push(match attr_name_node.text {
                            Some(ref text) => text.clone(),
                            None => String::new(), // TODO: maybe it's an error to have an empty node?
                        });
                    }

                    if vec.is_empty() {
                        return Err(Box::new(MissingChildNodeError::new(
                            child_node.name.clone(),
                            "attrName",
                        )));
                    }

                    attr_name_list = Some(vec);
                }
                _ => (),
            }
        }

        let common_time_node_data =
            common_time_node_data.ok_or_else(|| MissingChildNodeError::new(xml_node.name.clone(), "cTn"))?;
        let target_element =
            target_element.ok_or_else(|| MissingChildNodeError::new(xml_node.name.clone(), "tgtEl"))?;

        Ok(Self {
            additive,
            accumulate,
            transform_type,
            from,
            to,
            by,
            runtime_context,
            override_type,
            common_time_node_data,
            target_element,
            attr_name_list,
        })
    }
}

/// This element is used to describe behavior of media elements, such as sound or movies, in an animation.
///
/// # Xml example
///
/// ```xml
/// <p:audio>
///   <p:cMediaNode mute="1">
///     <p:cTn display="0" masterRel="sameClick">
///       <p:stCondLst> … </p:stCondLst>
///       <p:endCondLst> … </p:endCondLst>
///     </p:cTn>
///     <p:tgtEl> … </p:tgtEl>
///   </p:cMediaNode>
/// </p:audio>
/// ```
#[derive(Debug, Clone)]
pub struct TLCommonMediaNodeData {
    /// This attribute describes the volume of the media element.
    ///
    /// Defaults to 50000
    pub volume: Option<msoffice_shared::drawingml::PositiveFixedPercentage>,
    /// This attribute describes whether the media should be mute.
    ///
    /// Defaults to false
    pub mute: Option<bool>,
    /// This attribute describes the numbers of slides across which the media should play.
    ///
    /// Defaults to 1
    pub number_of_slides: Option<u32>,
    /// This attribute describes whether the media should be displayed when it is stopped.
    ///
    /// Defaults to true
    pub show_when_stopped: Option<bool>,
    pub common_time_node_data: Box<TLCommonTimeNodeData>,
    pub target_element: TLTimeTargetElement,
}

impl TLCommonMediaNodeData {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut volume = None;
        let mut mute = None;
        let mut number_of_slides = None;
        let mut show_when_stopped = None;

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "vol" => volume = Some(value.parse()?),
                "mute" => mute = Some(parse_xml_bool(value)?),
                "numSld" => number_of_slides = Some(value.parse()?),
                "showWhenStopped" => show_when_stopped = Some(parse_xml_bool(value)?),
                _ => (),
            }
        }

        let mut common_time_node_data = None;
        let mut target_element = None;

        for child_node in &xml_node.child_nodes {
            match child_node.local_name() {
                "cTn" => common_time_node_data = Some(Box::new(TLCommonTimeNodeData::from_xml_element(child_node)?)),
                "tgtEl" => target_element = Some(TLTimeTargetElement::from_xml_element(child_node)?),
                _ => (),
            }
        }

        let common_time_node_data =
            common_time_node_data.ok_or_else(|| MissingChildNodeError::new(xml_node.name.clone(), "cTn"))?;
        let target_element =
            target_element.ok_or_else(|| MissingChildNodeError::new(xml_node.name.clone(), "tgtEl"))?;

        Ok(Self {
            volume,
            mute,
            number_of_slides,
            show_when_stopped,
            common_time_node_data,
            target_element,
        })
    }
}

#[derive(Debug, Clone)]
pub struct TLBuildParagraph {
    pub build_common: TLBuildCommonAttributes,
    /// This attribute describe the build types.
    ///
    /// Defaults to TLParaBuildType::Whole
    pub build_type: Option<TLParaBuildType>,
    /// This attribute describes the build level for the paragraph. It is only supported in
    /// paragraph type builds i.e the build attribute shall also be set to "byParagraph" for this
    /// attribute to apply.
    ///
    /// Defaults to 1
    pub build_level: Option<u32>,
    /// This attribute indicates whether to animate the background of the shape associated with
    /// the text.
    ///
    /// Defaults to false
    pub animate_bg: Option<bool>,
    /// This attribute indicates whether to automatically update the "animateBg" setting to true
    /// when the shape associated with the text has a fill or line.
    ///
    /// Defaults to true
    pub auto_update_anim_bg: Option<bool>,
    /// This attribute is only supported in paragraph type builds. This specifies the direction of
    /// the build relative to the order of the elements in the container. When this is set to "true",
    /// the animations for the paragraphs are persisted in reverse order to the order of the
    /// paragraphs themselves such that the last paragraph animates first.
    ///
    /// Defaults to false
    pub reverse: Option<bool>,
    /// This attribute specifies time after which to automatically advance the build to the next
    /// step.
    ///
    /// Defaults to TLTime::Indefinite
    pub auto_advance_time: Option<TLTime>,
    pub template_list: Option<Vec<TLTemplate>>, // size: 0-9
}

impl TLBuildParagraph {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut shape_id = None;
        let mut group_id = None;
        let mut ui_expand = None;
        let mut build_type = None;
        let mut build_level = None;
        let mut animate_bg = None;
        let mut auto_update_anim_bg = None;
        let mut reverse = None;
        let mut auto_advance_time = None;

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "spid" => shape_id = Some(value.parse()?),
                "grpId" => group_id = Some(value.parse()?),
                "uiExpand" => ui_expand = Some(parse_xml_bool(value)?),
                "build" => build_type = Some(value.parse()?),
                "bldLvl" => build_level = Some(value.parse()?),
                "animBg" => animate_bg = Some(parse_xml_bool(value)?),
                "autoUpdateAnimBg" => auto_update_anim_bg = Some(parse_xml_bool(value)?),
                "rev" => reverse = Some(parse_xml_bool(value)?),
                "advAuto" => auto_advance_time = Some(value.parse()?),
                _ => (),
            }
        }

        let template_list = match xml_node.child_nodes.get(0) {
            Some(child_node) => {
                let mut vec = Vec::new();
                for template_node in &child_node.child_nodes {
                    vec.push(TLTemplate::from_xml_element(template_node)?);
                }
                Some(vec)
            }
            None => None,
        };

        let shape_id = shape_id.ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "spid"))?;
        let group_id = group_id.ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "grpId"))?;

        Ok(Self {
            build_common: TLBuildCommonAttributes {
                shape_id,
                group_id,
                ui_expand,
            },
            build_type,
            build_level,
            animate_bg,
            auto_update_anim_bg,
            reverse,
            auto_advance_time,
            template_list,
        })
    }
}

#[derive(Debug, Clone)]
pub struct TLPoint {
    /// This attribute describes the X coordinate.
    pub x: msoffice_shared::drawingml::Percentage,
    /// This attribute describes the Y coordinate.
    pub y: msoffice_shared::drawingml::Percentage,
}

impl TLPoint {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut x = None;
        let mut y = None;

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "x" => x = Some(value.parse()?),
                "y" => y = Some(value.parse()?),
                _ => (),
            }
        }

        let x = x.ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "x"))?;
        let y = y.ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "y"))?;

        Ok(Self { x, y })
    }
}

#[derive(Debug, Clone)]
pub enum TLTime {
    TimePoint(u32),
    Indefinite,
}

impl FromStr for TLTime {
    type Err = msoffice_shared::error::ParseEnumError;

    fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
        match s {
            "indefinite" => Ok(TLTime::Indefinite),
            _ => Ok(TLTime::TimePoint(s.parse().map_err(|_| Self::Err::new("TLTime"))?)),
        }
    }
}

#[derive(Debug, Clone)]
pub struct TLTemplate {
    /// This attribute describes the paragraph indent level to which this template effect applies.
    ///
    /// Defaults to 0
    pub level: Option<u32>,
    pub time_node_list: Vec<TimeNodeGroup>,
}

impl TLTemplate {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let level = match xml_node.attribute("lvl") {
            Some(value) => Some(value.parse()?),
            None => None,
        };

        let time_node_list = match xml_node.child_nodes.get(0) {
            Some(child_node) => {
                let mut vec = Vec::new();
                for time_node in &child_node.child_nodes {
                    vec.push(TimeNodeGroup::from_xml_element(time_node)?);
                }
                vec
            }
            None => return Err(Box::new(MissingChildNodeError::new(xml_node.name.clone(), "tnLst"))),
        };

        Ok(Self { level, time_node_list })
    }
}

#[derive(Debug, Clone)]
pub struct TLBuildCommonAttributes {
    /// This attribute specifies the shape to which the build applies.
    pub shape_id: msoffice_shared::drawingml::DrawingElementId,
    /// This attribute ties effects persisted in the animation to the build information. The
    /// attribute is used by the editor when changes to the build information are made.
    /// GroupIDs are unique for a given shape. They are not guaranteed to be unique IDs across
    /// all shapes on a slide.
    pub group_id: u32,
    /// This attribute describes the view option indicating if the build should be displayed
    /// expanded.
    ///
    /// Defaults to false
    pub ui_expand: Option<bool>,
}

#[derive(Debug, Clone)]
pub struct TLBuildDiagram {
    pub build_common: TLBuildCommonAttributes,
    /// This attribute describes how the diagram is built. The animation animates the sub-
    /// elements in the container in the particular order defined by this attribute.
    ///
    /// Defaults to TLDiagramBuildType::Whole
    pub build_type: Option<TLDiagramBuildType>,
}

impl TLBuildDiagram {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut shape_id = None;
        let mut group_id = None;
        let mut ui_expand = None;
        let mut build_type = None;

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "spid" => shape_id = Some(value.parse()?),
                "grpId" => group_id = Some(value.parse()?),
                "uiExpand" => ui_expand = Some(parse_xml_bool(value)?),
                "bld" => build_type = Some(value.parse()?),
                _ => (),
            }
        }

        let shape_id = shape_id.ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "spid"))?;
        let group_id = group_id.ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "grpId"))?;

        Ok(Self {
            build_common: TLBuildCommonAttributes {
                shape_id,
                group_id,
                ui_expand,
            },
            build_type,
        })
    }
}

#[derive(Debug, Clone)]
pub struct TLOleBuildChart {
    pub build_common: TLBuildCommonAttributes,
    /// This attribute describes how the diagram is built. The animation animates the sub-
    /// elements in the container in the particular order defined by this attribute.
    ///
    /// Defaults to TLOleChartBuildType::AllAtOnce
    pub build_type: Option<TLOleChartBuildType>,
    /// This attribute describes whether to animate the background of the shape.
    ///
    /// Defaults to true
    pub animate_bg: Option<bool>,
}

impl TLOleBuildChart {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut shape_id = None;
        let mut group_id = None;
        let mut ui_expand = None;
        let mut build_type = None;
        let mut animate_bg = None;

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "spid" => shape_id = Some(value.parse()?),
                "grpId" => group_id = Some(value.parse()?),
                "uiExpand" => ui_expand = Some(parse_xml_bool(value)?),
                "bld" => build_type = Some(value.parse()?),
                "animBg" => animate_bg = Some(parse_xml_bool(value)?),
                _ => (),
            }
        }

        let shape_id = shape_id.ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "spid"))?;
        let group_id = group_id.ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "grpId"))?;

        Ok(Self {
            build_common: TLBuildCommonAttributes {
                shape_id,
                group_id,
                ui_expand,
            },
            build_type,
            animate_bg,
        })
    }
}

#[derive(Debug, Clone)]
pub struct TLGraphicalObjectBuild {
    pub build_common: TLBuildCommonAttributes,
    pub build_choice: TLGraphicalObjectBuildChoice,
}

impl TLGraphicalObjectBuild {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut shape_id = None;
        let mut group_id = None;
        let mut ui_expand = None;

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "spid" => shape_id = Some(value.parse()?),
                "grpId" => group_id = Some(value.parse()?),
                "uiExpand" => ui_expand = Some(parse_xml_bool(value)?),
                _ => (),
            }
        }

        let build_choice = match xml_node.child_nodes.get(0) {
            Some(child_node) => TLGraphicalObjectBuildChoice::from_xml_element(child_node)?,
            None => {
                return Err(Box::new(MissingChildNodeError::new(
                    xml_node.name.clone(),
                    "TLGraphicalObjectBuildChoice",
                )))
            }
        };

        let shape_id = shape_id.ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "spid"))?;
        let group_id = group_id.ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "grpId"))?;

        Ok(Self {
            build_common: TLBuildCommonAttributes {
                shape_id,
                group_id,
                ui_expand,
            },
            build_choice,
        })
    }
}

#[derive(Debug, Clone)]
pub enum TLGraphicalObjectBuildChoice {
    /// This element specifies in the build list to build the entire graphical object as one entity.
    ///
    /// # Xml example
    ///
    /// Consider having a graph appear as on entity as opposed to by category. The <bldAsOne> element
    /// should be used as follows:
    ///
    /// ```xml
    /// <p:bldLst>
    ///   <p:bldGraphic spid="4" grpId="0">
    ///     <p:bldAsOne/>
    ///   </p:bldGraphic>
    /// </p:bldLst>
    /// ```
    BuildAsOne,
    /// This element specifies the animation properties of a graphical object's sub-elements.
    ///
    /// # Xml example
    ///
    /// Consider applying animation to a graphical element consisting of a diagram. The <bldSub> element
    /// should be used as follows:
    /// ```xml
    /// <p:bldLst>
    ///   <p:bldGraphic spid="5" grpId="0">
    ///     <p:bldSub>
    ///       <a:bldDgm bld="one"/>
    ///     </p:bldSub>
    ///   </p:bldGraphic>
    /// </p:bldLst>
    /// ```
    BuildSubElements(msoffice_shared::drawingml::AnimationGraphicalObjectBuildProperties),
}

impl TLGraphicalObjectBuildChoice {
    pub fn is_choice_member<T>(name: T) -> bool
    where
        T: AsRef<str>,
    {
        match name.as_ref() {
            "bldAsOne" | "bldSub" => true,
            _ => false,
        }
    }

    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        match xml_node.local_name() {
            "bldAsOne" => Ok(TLGraphicalObjectBuildChoice::BuildAsOne),
            "bldSub" => Ok(TLGraphicalObjectBuildChoice::BuildSubElements(
                msoffice_shared::drawingml::AnimationGraphicalObjectBuildProperties::from_xml_element(xml_node)?,
            )),
            _ => Err(Box::new(NotGroupMemberError::new(
                xml_node.name.clone(),
                "TLGraphicalObjectBuildChoice",
            ))),
        }
    }
}

#[derive(Debug, Clone)]
pub struct TLTimeNodeSequence {
    /// This attribute specifies if concurrency is enabled or disabled. By default this attribute has
    /// a value of "disabled". When the value is set to "enabled", the previous element is left
    /// enabled when advancing to the next element in a sequence instead of being ended. This
    /// is only relevant for advancing via the next condition element being triggered. The only
    /// other way to advance to the next element would be to have the current element end,
    /// which implies it is no longer concurrent.
    pub concurrent: Option<bool>,
    /// This attribute specifies what to do when going backwards in a sequence. By default it is
    /// set to TLPreviousActionType::None and nothing special is done. When the value is TLPreviousActionType::SkipTimed,
    /// the sequence continues to go backwards until it reaches a sequence element that was defined to begin
    /// only on the next condition element.
    pub prev_action_type: Option<TLPreviousActionType>,
    /// This attribute specifies what to do when going forward in sequence. By default this
    /// attribute has a value of TLNextActionType::None. When this is set to seek it seeks the element to a natural
    /// end time (not necessarily the actual end time).
    ///
    /// The natural end position is defined as the latest non-infinite end time of the children. If a
    /// child loops forever, the end of its first loop is used as its "end time" for the purposes of
    /// this calculation.
    ///
    /// Some container elements can have infinite durations due to an infinite-duration child
    /// element. The engine needs to recurse down through all infinite duration containers to
    /// calculate their natural duration in case a child might have non-infinite duration within it
    /// that needs to be taken into account.
    pub next_action_type: Option<TLNextActionType>,
    pub common_time_node_data: Box<TLCommonTimeNodeData>,
    /// This element describes a list of conditions that shall be met in order to go backwards in an animation sequence.
    ///
    /// # Xml example
    ///
    /// Consider trying to emphasize text within a shape by changing the size of its font.
    /// ```xml
    /// <p:seq concurrent="1" nextAc="seek">
    ///   <p:cTn id="2" dur="indefinite" nodeType="mainSeq">
    ///   </p:cTn>
    ///   <p:prevCondLst>
    ///     <p:cond evt="onPrev" delay="0">
    ///       <p:tgtEl>
    ///         <p:sldTgt/>
    ///       </p:tgtEl>
    ///     </p:cond>
    ///   </p:prevCondLst>
    ///   <p:nextCondLst>
    ///   </p:nextCondLst>
    /// </p:seq>
    /// ```
    pub prev_condition_list: Vec<TLTimeCondition>,
    /// This element describes a list of conditions that shall be met to advance to the next animation sequence.
    ///
    /// # Xml example
    ///
    /// Consider a shape with a text emphasis changing the size of its font.
    /// ```xml
    /// <p:seq concurrent="1" nextAc="seek">
    ///   <p:cTn id="2" dur="indefinite" nodeType="mainSeq"> … </p:cTn>
    ///   <p:prevCondLst> … </p:prevCondLst>
    ///   <p:nextCondLst>
    ///     <p:cond evt="onNext" delay="0">
    ///       <p:tgtEl>
    ///         <p:sldTgt/>
    ///       </p:tgtEl>
    ///     </p:cond>
    ///   </p:nextCondLst>
    /// </p:seq>
    /// ```
    pub next_condition_list: Vec<TLTimeCondition>,
}

impl TLTimeNodeSequence {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut concurrent = None;
        let mut prev_action_type = None;
        let mut next_action_type = None;

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "concurrent" => concurrent = Some(parse_xml_bool(value)?),
                "prevAc" => prev_action_type = Some(value.parse()?),
                "nextAc" => next_action_type = Some(value.parse()?),
                _ => (),
            }
        }

        let mut common_time_node_data = None;
        let mut prev_condition_list = Vec::new();
        let mut next_condition_list = Vec::new();

        for child_node in &xml_node.child_nodes {
            match child_node.local_name() {
                "cTn" => common_time_node_data = Some(Box::new(TLCommonTimeNodeData::from_xml_element(child_node)?)),
                "prevCondLst" => {
                    for condition_node in &child_node.child_nodes {
                        prev_condition_list.push(TLTimeCondition::from_xml_element(condition_node)?);
                    }
                }
                "nextCondLst" => {
                    for condition_node in &child_node.child_nodes {
                        next_condition_list.push(TLTimeCondition::from_xml_element(condition_node)?);
                    }
                }
                _ => (),
            }
        }

        let common_time_node_data =
            common_time_node_data.ok_or_else(|| MissingChildNodeError::new(xml_node.name.clone(), "cTn"))?;

        Ok(Self {
            concurrent,
            prev_action_type,
            next_action_type,
            common_time_node_data,
            prev_condition_list,
            next_condition_list,
        })
    }
}

#[derive(Debug, Clone)]
pub struct TLAnimateBehavior {
    /// This attribute specifies a relative offset value for the animation with respect to its
    /// position before the start of the animation.
    pub by: Option<String>,
    /// This attribute specifies the starting value of the animation.
    pub from: Option<String>,
    /// This attribute specifies the ending value for the animation as a percentage.
    pub to: Option<String>,
    /// This attribute specifies the interpolation mode for the animation.
    pub calc_mode: Option<TLAnimateBehaviorCalcMode>,
    /// This attribute specifies the type of property value.
    pub value_type: Option<TLAnimateBehaviorValueType>,
    pub common_behavior_data: Box<TLCommonBehaviorData>,
    /// This element specifies a list of time animated value elements.
    ///
    /// ```xml
    /// <p:anim calcmode="lin" valueType="num">
    ///   <p:cBhvr additive="base"> … </p:cBhvr>
    ///   <p:tavLst>
    ///     <p:tav tm="0%">
    ///       <p:val>
    ///         <p:strVal val="1+#ppt_h/2"/>
    ///       </p:val>
    ///     </p:tav>
    ///     <p:tav tm="100000">
    ///       <p:val>
    ///         <p:strVal val="#ppt_y"/>
    ///       </p:val>
    ///     </p:tav>
    ///   </p:tavLst>
    /// </p:anim>
    /// ```
    pub time_animate_value_list: Option<Vec<TLTimeAnimateValue>>,
}

impl TLAnimateBehavior {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut by = None;
        let mut from = None;
        let mut to = None;
        let mut calc_mode = None;
        let mut value_type = None;

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "by" => by = Some(value.clone()),
                "from" => from = Some(value.clone()),
                "to" => to = Some(value.clone()),
                "calcmode" => calc_mode = Some(value.parse()?),
                "valueType" => value_type = Some(value.parse()?),
                _ => (),
            }
        }

        let mut common_behavior_data = None;
        let mut time_animate_value_list = None;

        for child_node in &xml_node.child_nodes {
            match child_node.local_name() {
                "cBhvr" => common_behavior_data = Some(Box::new(TLCommonBehaviorData::from_xml_element(child_node)?)),
                "tavLst" => {
                    let mut vec = Vec::new();
                    for tav_node in &child_node.child_nodes {
                        vec.push(TLTimeAnimateValue::from_xml_element(tav_node)?);
                    }

                    time_animate_value_list = Some(vec);
                }
                _ => (),
            }
        }

        let common_behavior_data =
            common_behavior_data.ok_or_else(|| MissingChildNodeError::new(xml_node.name.clone(), "cBhvr"))?;

        Ok(Self {
            by,
            from,
            to,
            calc_mode,
            value_type,
            common_behavior_data,
            time_animate_value_list,
        })
    }
}

#[derive(Debug, Clone)]
pub struct TLAnimateColorBehavior {
    /// This attribute specifies the color space in which to interpolate the animation. Values for
    /// example can be HSL & RGB.
    ///
    /// The values for from/to/by/etc. can still be specified in any supported color format
    /// without affecting the color space within which the animation happens.
    ///
    /// The RGB color space is best used for doing animations between two different colors since
    /// it doesn't require going through any other hues between the two colors specified. The
    /// HSL space is useful for animating through a rainbow of colors or for modifying just the
    /// saturation by 30% for example.
    pub color_space: Option<TLAnimateColorSpace>,
    /// This attribute specifies which direction to cycle the hue around the color wheel. Values
    /// are clockwise or counter clockwise. Default is clockwise.
    pub direction: Option<TLAnimateColorDirection>,
    pub common_behavior_data: Box<TLCommonBehaviorData>,
    /// This element describes the relative offset value for the color animation.
    ///
    /// # Xml example
    ///
    /// ```xml
    /// <p:animClr clrSpc="hsl">
    ///   <p:cBhvr>
    ///     <p:cTn id="8" dur="500" fill="hold"/>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="4"/>
    ///     </p:tgtEl>
    ///     <p:attrNameLst>
    ///       <p:attrName>stroke.color</p:attrName>
    ///     </p:attrNameLst>
    ///   </p:cBhvr>
    ///   <p:by>
    ///     <p:hsl h="0" s="0" l="0"/>
    ///   </p:by>
    /// </p:animClr>
    /// ```
    pub by: Option<TLByAnimateColorTransform>,
    /// This element is used to specify the starting color of the target element.
    ///
    /// # Xml example
    ///
    /// ```xml
    /// <p:animClr clrSpc="rgb" dir="cw">
    ///   <p:cBhvr>
    ///     <p:cTn id="6" dur="2000" fill="hold"/>
    ///     <p:tgtEl> … </p:tgtEl>
    ///     <p:attrNameLst>
    ///       <p:attrName>fillcolor</p:attrName>
    ///     </p:attrNameLst>
    ///   </p:cBhvr>
    ///   <p:from>
    ///     <a:schemeClr val="accent3"/>
    ///   </p:from>
    ///   <p:to>
    ///     <a:schemeClr val="accent2"/>
    ///   </p:to>
    /// </p:animClr>
    /// ```
    pub from: Option<msoffice_shared::drawingml::Color>,
    /// This element specifies the resulting color for the animation color change.
    ///
    /// # Xml example
    ///
    /// Consider emphasize a shape by changing its fill color from blue to red. The <to> element should be
    /// used as follows:
    /// ```xml
    /// <p:childTnLst>
    ///   <p:animClr clrSpc="rgb">
    ///     <p:cBhvr> … </p:cBhvr>
    ///     <p:to>
    ///       <a:schemeClr val="accent2"/>
    ///     </p:to>
    ///   </p:animClr>
    /// </p:childTnLst>
    /// ```
    pub to: Option<msoffice_shared::drawingml::Color>,
}

impl TLAnimateColorBehavior {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        use msoffice_shared::drawingml::Color;

        let mut color_space = None;
        let mut direction = None;

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "clrSpc" => color_space = Some(value.parse()?),
                "dir" => direction = Some(value.parse()?),
                _ => (),
            }
        }

        let mut common_behavior_data = None;
        let mut by = None;
        let mut from = None;
        let mut to = None;

        for child_node in &xml_node.child_nodes {
            match child_node.local_name() {
                "cBhvr" => common_behavior_data = Some(Box::new(TLCommonBehaviorData::from_xml_element(child_node)?)),
                "by" => {
                    let by_node = child_node.child_nodes.get(0).ok_or_else(|| {
                        MissingChildNodeError::new(child_node.name.clone(), "TLByAnimateColorTransform")
                    })?;
                    by = Some(TLByAnimateColorTransform::from_xml_element(by_node)?);
                }
                "from" => {
                    let color_node = child_node
                        .child_nodes
                        .get(0)
                        .ok_or_else(|| MissingChildNodeError::new(child_node.name.clone(), "EG_Color"))?;
                    from = Some(Color::from_xml_element(color_node)?);
                }
                "to" => {
                    let color_node = child_node
                        .child_nodes
                        .get(0)
                        .ok_or_else(|| MissingChildNodeError::new(child_node.name.clone(), "EG_Color"))?;
                    to = Some(Color::from_xml_element(color_node)?);
                }
                _ => (),
            }
        }

        let common_behavior_data =
            common_behavior_data.ok_or_else(|| MissingChildNodeError::new(xml_node.name.clone(), "cBhvr"))?;

        Ok(Self {
            color_space,
            direction,
            common_behavior_data,
            by,
            from,
            to,
        })
    }
}

#[derive(Debug, Clone)]
pub struct TLAnimateEffectBehavior {
    /// This attribute specifies whether to transition the element in or out or treat it as a static
    /// filter. The values are "None", "In" and "Out", and the default value is "In".
    ///
    /// When a value of "In" is specified, the element is not visible at the start of the animation
    /// and is completely visible be the end of the duration. When "Out" is specified, the element
    /// is visible at the start and not visible at the end of the effect. This visibility is in addition to
    /// the effect of setting CSS visibility or display attributes.
    pub transition: Option<TLAnimateEffectTransition>,
    /// This attribute specifies the animation types and subtypes to be used for the effect.
    /// Multiple animations are allowed to be listed so that in the event that a superseding
    /// animation (leftmost) cannot be rendered, a fallback animation is available. That is, the
    /// rendering application parses the list from left to right until a supported animation is
    /// found.
    ///
    /// The syntax used for the filter attribute value is as follows: "type(subtype);type(subtype)".
    /// Subtype can be a string value such as "fromLeft" or a numerical value depending on the
    /// type specified.
    ///
    /// # Xml example
    ///
    /// ```xml
    /// <p:animEffect transition="in" filter="blinds(horizontal);blinds(vertical)">
    ///   <p:cBhvr>
    ///     <p:cTn id="7" dur="500"/>
    ///     <p:tgtEl>
    ///       <p:spTgtspid="5"/>
    ///     </p:tgtEl>
    ///   </p:cBhvr>
    /// </p:animEffect>
    /// ```
    ///
    /// There are two animation filters shown in this example. The first is the blinds (horizontal),
    /// which the rendering application is to use as the primary animation effect. If, however,
    /// the rendering application does not support this animation, the blinds (vertical) animation
    /// is used. In this example there are only two animation filters listed, a primary and a
    /// fallback, but it is possible to list multiple fallback filters using the syntax defined above.
    pub filter: Option<String>,
    /// This attribute specifies a list of properties that coincide with the effect specified.
    /// Although there are many animation types allowed, this attribute allows the setting of
    /// specific property settings in order to describe an even wider variety of animation types.
    ///
    /// The syntax used for the prLst attribute value is as follows: “name:value;name:value”.
    /// When multiple animation types are listed in the filter attribute, the rendering application
    /// attempts to apply each property value even though some might not apply to it.
    ///
    /// # Xml example
    ///
    /// ```xml
    /// <p:animEffect filter="image" prLst="opacity: 0.5">
    ///   <p:cBhvr rctx="IE">
    ///     <p:cTn id="7" dur="indefinite"/>
    ///     <p:tgtEl>
    ///       <p:spTgtspid="3"/>
    ///     </p:tgtEl>
    ///   </p:cBhvr>
    /// </p:animEffect>
    /// ```
    ///
    /// The animation filter specified is an image filter type that has a specific property called
    /// opacity set to a value of 0.5.
    pub property_list: Option<String>,
    pub common_behavior_data: Box<TLCommonBehaviorData>,
    /// This element defines the progression of an animation. The default for the way animation progress happens
    /// through an animEffect is a linear ramp from 0 to 1, starting at the effect’s begin time & ending at the effect’s
    /// end time. When you specify a value for the progress attribute, you are overriding this default behaviour. The
    /// value between 0 and 1 represents a percentage through the effect, where 0 is 0% and 1 is 100%.
    ///
    /// Each animEffect is in fact an object-based transition. These transitions can be specified as “In” (where the object
    /// is not visible at 0% and becomes completely visible at 100%) or “Out” (where the object is visible at 0% and
    /// becomes completely invisible at 100%). You would set the progress attribute if you want to use the animEffect
    /// as a “static” effect, where the transition properties do not actually change over time. As an alternative to using
    /// the progress attribute, you can use the tmFilter (time filter), which is a base attribute of any effect/timenode, to
    /// specify the way that progress through an effect should be performed dynamically.
    pub progress: Option<TLAnimVariant>,
}

impl TLAnimateEffectBehavior {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut transition = None;
        let mut filter = None;
        let mut property_list = None;

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "transition" => transition = Some(value.parse()?),
                "filter" => filter = Some(value.clone()),
                "prLst" => property_list = Some(value.clone()),
                _ => (),
            }
        }

        let mut common_behavior_data = None;
        let mut progress = None;

        for child_node in &xml_node.child_nodes {
            match child_node.local_name() {
                "cBhvr" => common_behavior_data = Some(Box::new(TLCommonBehaviorData::from_xml_element(child_node)?)),
                "progress" => {
                    let progress_node = child_node
                        .child_nodes
                        .get(0)
                        .ok_or_else(|| MissingChildNodeError::new(child_node.name.clone(), "CT_TLAnimVariant"))?;
                    progress = Some(TLAnimVariant::from_xml_element(progress_node)?);
                }
                _ => (),
            }
        }

        let common_behavior_data =
            common_behavior_data.ok_or_else(|| MissingChildNodeError::new(xml_node.name.clone(), "cBhvr"))?;

        Ok(Self {
            transition,
            filter,
            property_list,
            common_behavior_data,
            progress,
        })
    }
}

#[derive(Debug, Clone)]
pub struct TLAnimateMotionBehavior {
    /// Specifies what the origin of the motion path is relative to such as the layout of the slide,
    /// or the parent.
    pub origin: Option<TLAnimateMotionBehaviorOrigin>,
    /// Specifies the path primitive followed by coordinates for the animation motion. The
    /// allowed values that are understood within a path are as follows:
    ///
    /// M = move to, L = line to, C = curve to, Z=close loop, E=end
    /// UPPERCASE = absolute coords, lowercase = relative coords
    /// Thus total allowed set = {M,L,C,Z,E,m,l,c,z,e)
    ///
    /// # Example
    ///
    /// The following string is a sample path.
    /// path: “M 0 0 L 1 1 c 1 2 3 4 4 4 Z”
    pub path: Option<String>,
    /// This attribute specifies how the motion path moves when the target element is moved.
    pub path_edit_mode: Option<TLAnimateMotionPathEditMode>,
    /// The attribute describes the relative angle of the motion path.
    pub rotate_angle: Option<msoffice_shared::drawingml::Angle>,
    /// This attribute describes the point type of the points in the path attribute. The allowed
    /// values that are understood for the ptsTypes attribute are as follows:
    ///
    /// A = Auto, F = Corner, T = Straight, S = Smooth
    /// UPPERCASE = Straight Line follows point, lowercase = curve follows point.
    /// Thus, the total allowed set = {A,F,T,S,a,f,t,s}
    pub points_types: Option<String>,
    pub common_behavior_data: Box<TLCommonBehaviorData>,
    /// This element describes the relative offset value for the animation.
    ///
    /// # Xml example
    ///
    /// ```xml
    /// <p:animScale>
    ///   <p:cBhvr>
    ///     <p:cTn id="6" dur="2000" fill="hold"/>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="4"/>
    ///     </p:tgtEl>
    ///   </p:cBhvr>
    ///   <p:by x="150.000%" y="150.000%"/>
    /// </p:animScale>
    /// ```
    pub by: Option<TLPoint>,
    pub from: Option<TLPoint>,
    /// This element specifies the target location for an animation motion or animation scale effect
    ///
    /// # Xml example
    ///
    /// Consider an animation with a "light speed" entrance effect.
    /// ```xml
    /// <p:animScale>
    ///   <p:cBhvr>
    ///     <p:cTn id="9" dur="200" decel="10.5%" autoRev="1" fill="hold">
    ///       <p:stCondLst>
    ///         <p:cond delay="600"/>
    ///       </p:stCondLst>
    ///     </p:cTn>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="4"/>
    ///     </p:tgtEl>
    ///   </p:cBhvr>
    ///   <p:from x="100%" y="100%"/>
    ///   <p:to x="80%" y="100%"/>
    /// </p:animScale>
    /// ```
    pub to: Option<TLPoint>,
    /// This element describes the center of the rotation used to rotate a motion path by X angle.
    ///
    /// # Xml example
    ///
    /// For example, suppose we have a simple animation with a checkerbox text entrance.
    /// ```xml
    /// <p:animMotion origin="layout" path="M 0 0 L 0.25 0.33333 E" pathEditMode="relative" rAng="0" ptsTypes="">
    ///   <p:cBhvr>
    ///     <p:cTn id="6" dur="2000" fill="hold"/>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="3"/>
    ///     </p:tgtEl>
    ///     <p:attrNameLst>
    ///       <p:attrName>ppt_x</p:attrName>
    ///       <p:attrName>ppt_y</p:attrName>
    ///     </p:attrNameLst>
    ///   </p:cBhvr>
    ///   <p:rCtr x="56.7%" y="83.4%"/>
    /// </p:animMotion>
    /// ```
    pub rotation_center: Option<TLPoint>,
}

impl TLAnimateMotionBehavior {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut origin = None;
        let mut path = None;
        let mut path_edit_mode = None;
        let mut rotate_angle = None;
        let mut points_types = None;

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "origin" => origin = Some(value.parse()?),
                "path" => path = Some(value.clone()),
                "pathEditMode" => path_edit_mode = Some(value.parse()?),
                "rAng" => rotate_angle = Some(value.parse()?),
                "ptsTypes" => points_types = Some(value.clone()),
                _ => (),
            }
        }

        let mut common_behavior_data = None;
        let mut by = None;
        let mut from = None;
        let mut to = None;
        let mut rotation_center = None;

        for child_node in &xml_node.child_nodes {
            match child_node.local_name() {
                "cBhvr" => common_behavior_data = Some(Box::new(TLCommonBehaviorData::from_xml_element(child_node)?)),
                "by" => by = Some(TLPoint::from_xml_element(child_node)?),
                "from" => from = Some(TLPoint::from_xml_element(child_node)?),
                "to" => to = Some(TLPoint::from_xml_element(child_node)?),
                "rCtr" => rotation_center = Some(TLPoint::from_xml_element(child_node)?),
                _ => (),
            }
        }

        let common_behavior_data =
            common_behavior_data.ok_or_else(|| MissingChildNodeError::new(xml_node.name.clone(), "cBhvr"))?;

        Ok(Self {
            origin,
            path,
            path_edit_mode,
            rotate_angle,
            points_types,
            common_behavior_data,
            by,
            from,
            to,
            rotation_center,
        })
    }
}

#[derive(Debug, Clone)]
pub struct TLAnimateRotationBehavior {
    /// This attribute describes the relative offset value for the animation.
    pub by: Option<msoffice_shared::drawingml::Angle>,
    /// This attribute describes the starting value for the animation.
    pub from: Option<msoffice_shared::drawingml::Angle>,
    /// This attribute describes the ending value for the animation.
    pub to: Option<msoffice_shared::drawingml::Angle>,
    pub common_behavior_data: Box<TLCommonBehaviorData>,
}

impl TLAnimateRotationBehavior {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut by = None;
        let mut from = None;
        let mut to = None;

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "by" => by = Some(value.parse()?),
                "from" => from = Some(value.parse()?),
                "to" => to = Some(value.parse()?),
                _ => (),
            }
        }

        let common_behavior_data_node = xml_node
            .child_nodes
            .get(0)
            .ok_or_else(|| MissingChildNodeError::new(xml_node.name.clone(), "cBhvr"))?;
        let common_behavior_data = Box::new(TLCommonBehaviorData::from_xml_element(common_behavior_data_node)?);

        Ok(Self {
            by,
            from,
            to,
            common_behavior_data,
        })
    }
}

#[derive(Debug, Clone)]
pub struct TLAnimateScaleBehavior {
    /// This attribute specifies whether to zoom the contents of an object when doing a scaling
    /// animation.
    pub zoom_contents: Option<bool>,
    pub common_behavior_data: Box<TLCommonBehaviorData>,
    /// This element describes the relative offset value for the animation.
    ///
    /// # Xml example
    ///
    /// ```xml
    /// <p:animScale>
    ///   <p:cBhvr>
    ///     <p:cTn id="6" dur="2000" fill="hold"/>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="4"/>
    ///     </p:tgtEl>
    ///   </p:cBhvr>
    ///   <p:by x="150.000%" y="150.000%"/>
    /// </p:animScale>
    /// ```
    pub by: Option<TLPoint>,
    /// This element specifies an x/y co-ordinate to start the animation from.
    ///
    /// # Xml example
    ///
    /// ```xml
    /// <p:animScale>
    ///   <p:cBhvr>
    ///     <p:cTn> … </p:cTn>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="4"/>
    ///     </p:tgtEl>
    ///   </p:cBhvr>
    ///   <p:from x="100%" y="100%"/>
    ///   <p:to x="80%" y="100%"/>
    /// </p:animScale>
    /// ```
    pub from: Option<TLPoint>,
    /// This element specifies the target location for an animation motion or animation scale effect
    ///
    /// # Xml example
    ///
    /// Consider an animation with a "light speed" entrance effect.
    /// ```xml
    /// <p:animScale>
    ///   <p:cBhvr>
    ///     <p:cTn id="9" dur="200" decel="10.5%" autoRev="1" fill="hold">
    ///       <p:stCondLst>
    ///         <p:cond delay="600"/>
    ///       </p:stCondLst>
    ///     </p:cTn>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="4"/>
    ///     </p:tgtEl>
    ///   </p:cBhvr>
    ///   <p:from x="100%" y="100%"/>
    ///   <p:to x="80%" y="100%"/>
    /// </p:animScale>
    /// ```
    pub to: Option<TLPoint>,
}

impl TLAnimateScaleBehavior {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let zoom_contents = match xml_node.attribute("zoomContents") {
            Some(value) => Some(parse_xml_bool(value)?),
            None => None,
        };

        let mut common_behavior_data = None;
        let mut by = None;
        let mut from = None;
        let mut to = None;

        for child_node in &xml_node.child_nodes {
            match child_node.local_name() {
                "cBhvr" => common_behavior_data = Some(Box::new(TLCommonBehaviorData::from_xml_element(child_node)?)),
                "by" => by = Some(TLPoint::from_xml_element(child_node)?),
                "from" => from = Some(TLPoint::from_xml_element(child_node)?),
                "to" => to = Some(TLPoint::from_xml_element(child_node)?),
                _ => (),
            }
        }

        let common_behavior_data =
            common_behavior_data.ok_or_else(|| MissingChildNodeError::new(xml_node.name.clone(), "cBhvr"))?;

        Ok(Self {
            zoom_contents,
            common_behavior_data,
            by,
            from,
            to,
        })
    }
}

#[derive(Debug, Clone)]
pub struct TLCommandBehavior {
    /// This attribute specifies the kind of command that is issued by the rendering application to
    /// the appropriate target application or object.
    ///
    /// There are three possible values, call, evt, and verb. A call command type is used to
    /// specify the class of commands that can then be issued.
    ///
    /// * Call commands: This command type is used to call methods on the object specified (play(), pause(), etc.)
    ///
    /// * Event commands: This command type is used to set an event for the object at this point in the timeline
    ///                   (onstopaudio, etc.)
    ///
    /// * Verb Commands: This command type is used to set verbs for the object to occur at this point in the timeline
    ///                  (0, 1, etc.)
    pub command_type: Option<TLCommandType>,
    /// This attribute defines the actual command to be issued. Depending on the command
    /// specified, the actual command can be made to invoke a wide range of actions on the
    /// linked or embedded object
    ///
    /// Reserved Values (when command_type == TLCommandType::Call):
    /// * play: play corresponding media
    /// * playFrom(s): play corresponding media starting from s, where s is the number of
    ///                seconds from the beginning of the clip
    /// * pause: pause corresponding media
    /// * resume: resume play of corresponding media
    /// * stop: stop play of corresponding media
    /// * togglePause: play corresponding media if media is already paused, pause
    ///                corresponding media if media is already playing. If the corresponding
    ///                media is not active, this command restarts the media and plays from
    ///                its beginning.
    ///
    /// Reserved Values (when command_type == TLCommandType::Event):
    /// * onstopaudio: stop play of all audio
    ///
    /// Reserved Values (when command_type == TLCommandType::Verb):
    /// * 0: Open the object for editing
    /// * 1: Open the object for viewing
    ///
    /// The value of the cmd attribute shall be the string representation of an integer that
    /// represents the embedded object verb number. This verb number determines the action
    /// that the rendering application should take corresponding to this object when this point in
    /// the animation is reached.
    ///
    /// # Xml example
    ///
    /// ```xml
    /// <p:cmd type="evt" cmd="onstopaudio">
    ///   <p:cBhvr>
    ///     <p:cTn display="0" masterRel="sameClick">
    ///       <p:stCondLst>
    ///         <p:cond evt="begin" delay="0">
    ///           <p:tn val="5"/>
    ///         </p:cond>
    ///       </p:stCondLst>
    ///     </p:cTn>
    ///     <p:tgtEl>
    ///       <p:sldTgt/>
    ///     </p:tgtEl>
    ///   </p:cBhvr>
    /// </p:cmd>
    /// ```
    ///
    /// In the above example, the event of onstopaudio stops all audio from playing once this
    /// particular animation is reached in the timeline.
    pub command: Option<String>,
    pub common_behavior_data: Box<TLCommonBehaviorData>,
}

impl TLCommandBehavior {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut command_type = None;
        let mut command = None;

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "type" => command_type = Some(value.parse()?),
                "cmd" => command = Some(value.clone()),
                _ => (),
            }
        }

        let common_behavior_data_node = xml_node
            .child_nodes
            .get(0)
            .ok_or_else(|| MissingChildNodeError::new(xml_node.name.clone(), "cBhvr"))?;
        let common_behavior_data = Box::new(TLCommonBehaviorData::from_xml_element(common_behavior_data_node)?);

        Ok(Self {
            command_type,
            command,
            common_behavior_data,
        })
    }
}

#[derive(Debug, Clone)]
pub struct TLSetBehavior {
    pub common_behavior_data: Box<TLCommonBehaviorData>,
    /// The element specifies the certain attribute of a time node after an animation effect.
    ///
    /// # Xml example
    ///
    /// Consider an animation effect that leaves a string value visible afterwards. The <to> element should
    /// be used as follows:
    /// ```xml
    /// <p:childTnLst>
    ///   <p:set>
    ///     <p:cBhvr> … </p:cBhvr>
    ///     <p:to>
    ///       <p:strVal val="visible"/>
    ///     </p:to>
    ///   </p:set>
    ///   <p:anim calcmode="lin" valueType="num"> … </p:anim> …
    /// </p:childTnLst>
    /// ```
    pub to: Option<TLAnimVariant>,
}

impl TLSetBehavior {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut common_behavior_data = None;
        let mut to = None;

        for child_node in &xml_node.child_nodes {
            match child_node.local_name() {
                "cBhvr" => common_behavior_data = Some(Box::new(TLCommonBehaviorData::from_xml_element(child_node)?)),
                "to" => {
                    let to_node = child_node
                        .child_nodes
                        .get(0)
                        .ok_or_else(|| MissingChildNodeError::new(child_node.name.clone(), "CT_TLAnimVariant"))?;
                    to = Some(TLAnimVariant::from_xml_element(to_node)?);
                }
                _ => (),
            }
        }

        let common_behavior_data =
            common_behavior_data.ok_or_else(|| MissingChildNodeError::new(xml_node.name.clone(), "cBhvr"))?;

        Ok(Self {
            common_behavior_data,
            to,
        })
    }
}

#[derive(Debug, Clone)]
pub struct TLMediaNodeAudio {
    /// This attribute indicates whether the audio is a narration for the slide.
    ///
    /// Defaults to false
    pub is_narration: Option<bool>,
    pub common_media_node_data: Box<TLCommonMediaNodeData>,
}

impl TLMediaNodeAudio {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let is_narration = match xml_node.attribute("isNarration") {
            Some(value) => Some(parse_xml_bool(value)?),
            None => None,
        };

        let common_media_node_data_node = xml_node
            .child_nodes
            .get(0)
            .ok_or_else(|| MissingChildNodeError::new(xml_node.name.clone(), "cMediaNode"))?;
        let common_media_node_data = Box::new(TLCommonMediaNodeData::from_xml_element(common_media_node_data_node)?);

        Ok(Self {
            is_narration,
            common_media_node_data,
        })
    }
}

#[derive(Debug, Clone)]
pub struct TLMediaNodeVideo {
    /// This attribute specifies if the video is displayed in full-screen.
    ///
    /// Defaults to false
    pub fullscreen: Option<bool>,
    pub common_media_node_data: Box<TLCommonMediaNodeData>,
}

impl TLMediaNodeVideo {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let fullscreen = match xml_node.attribute("fullScrn") {
            Some(value) => Some(parse_xml_bool(value)?),
            None => None,
        };

        let common_media_node_data_node = xml_node
            .child_nodes
            .get(0)
            .ok_or_else(|| MissingChildNodeError::new(xml_node.name.clone(), "cMediaNode"))?;
        let common_media_node_data = Box::new(TLCommonMediaNodeData::from_xml_element(common_media_node_data_node)?);

        Ok(Self {
            fullscreen,
            common_media_node_data,
        })
    }
}

/// This element defines a "keypoint" in animation interpolation.
///
/// # Xml example
///
/// Consider a shape with a "fly-in" animation. The <tav> element should be used as follows:
/// ```xml
/// <p:anim calcmode="lin" valueType="num">
///   <p:cBhvr additive="base"> … </p:cBhvr>
///   <p:tavLst>
///     <p:tav tm="0%">
///       <p:val>
///         <p:strVal val="1+#ppt_h/2"/>
///       </p:val>
///     </p:tav>
///     <p:tav tm="100%">
///       <p:val>
///         <p:strVal val="#ppt_y"/>
///       </p:val>
///     </p:tav>
///   </p:tavLst>
/// </p:anim>
/// ```
#[derive(Default, Debug, Clone)]
pub struct TLTimeAnimateValue {
    /// This attribute specifies the time at which the attribute being animated takes on the value.
    ///
    /// Defaults to TLTimeAnimateValueTime::Indefinite
    pub time: Option<TLTimeAnimateValueTime>,
    /// This attribute allows for the specification of a formula to be used for describing a
    /// complex motion for an animated object. The formula manipulates the motion of the
    /// object by modifying a property of the object over a specified period of time. Each formula
    /// has zero or more inputs specified by the ($) symbol, zero or more variables specified by
    /// the (#) symbol pre-pended to the variable name and a target variable which is specified
    /// by the previously specified attrName element. The formula can contain one or more of
    /// any of the constants, operators or functions listed below. In addition to this, the formula
    /// can also contain floating point numbers and parentheses.
    ///
    /// Mathematical operations have the following order of precedence, listed from lowest to
    /// highest. Operators listed on the same line have equal precedence.
    ///
    /// * “+”, “-“
    /// * “*”, “/”, “%”
    /// * “^”
    /// * Unary minus, Unary plus (e.g. -2, meaning 3*-2 is the same as 3*(-2))
    /// * Variables, Constants (including numbers) and Functions (as listed previously)
    ///
    /// # Language Description
    ///
    /// Digit       = '0' | '1' | ‘2’ | ‘3’ | ‘4’ | ‘5’ | ‘6’ | ‘7’ | ‘8’ | '9' ;
    ///
    /// number      = digit , { digit } ;
    ///
    /// exponent    = [ '-' ] , ( 'e' | 'E' ) , number ;
    ///
    /// value       = number , [ '.' number ] , [ exponent ] ;
    ///
    /// variable    = '$' | 'ppt_x' | 'ppt_y' | 'ppt_w' | 'ppt_h' ;
    ///
    /// constant    = value | 'pi' | 'e' ;
    ///
    /// ident       = 'abs' | ‘acos’ | ‘asin’ | ‘atan’ | ‘ceil’
    ///               | ‘cos’ | ‘cosh’ | ‘deg’ | ‘exp’ | ‘floor’ | ‘ln’
    ///               | ‘max’ | ‘min’ | ‘rad’ | ‘rand’ | ‘sin’ | ‘sinh’
    ///               | ‘sqrt’ | ‘tan’ | 'tanh' ;
    ///
    /// function    = ident , '(' , formula [ ',' , formula ] , ')' ;
    ///
    /// formula     = term , { [ '+' | '-' ] , term } ;
    ///
    /// term        = power , { [ '*' | '/' | '%' ] , power } ;
    ///
    /// power       = unary [ '^' , unary ] ;
    ///
    /// unary       = [ '+' | '-' ] , factor ;
    ///
    /// factor      = variable | constant | function | parens ;
    ///
    /// parens      = '(' , formula , ')' ;
    ///
    /// ## Note
    ///
    /// Formulas can only support a calcMode (Calculation Mode) of linear or discrete. If
    /// another calcMode is specified or no calcMode is specified then a calcMode of linear is
    /// assumed.
    ///
    /// Any additional characters in the formula string that are not contained within the
    /// set described are considered invalid.
    ///
    /// # Variables
    ///
    /// |Name       |Description                                        |
    /// |-----------|---------------------------------------------------|
    /// |$          |Formula input                                      |
    /// |ppt_x      |Pre-animation x position of the object on the slide|
    /// |ppt_y      |Pre-animation y position of the object on the slide|
    /// |ppt_w      |Pre-animation width of the object                  |
    /// |ppt_h      |Pre-animation height of the object                 |
    ///
    /// # Constants
    ///
    /// |Name       |Description                                        |
    /// |-----------|---------------------------------------------------|
    /// |pi         |Mathematical constant pi                           |
    /// |e          |Mathematical constant e                            |
    ///
    /// # Operators
    ///
    /// |Name       |Description        |Usage                                  |
    /// |-----------|-------------------|---------------------------------------|
    /// |+          |Addition           |“x+y”, adds x to the value y           |
    /// |-          |Subtraction        |“x-y”, subtracts y from the value x    |
    /// |*          |Multiplication     |“x*y”, multiplies x by the value y     |
    /// |/          |Division           |“x/y”, divides x by the value y        |
    /// |%          |Modulus            |“x%y”, the remainder of x/y            |
    /// |^          |Power              |“x^y”, x raised to the power y         |
    ///
    /// # Functions
    ///
    /// |Name       |Description                |Usage                                                              |
    /// |-----------|---------------------------|-------------------------------------------------------------------|
    /// |abs        |Absolute value             |“abs(x)”, absolute value of x                                      |
    /// |acos       |Arc Cosine                 |“acos(x)”, arc cosine of the value x                               |
    /// |asin       |Arc Sine                   |“asin(x)”, arc sine of the value x                                 |
    /// |atan       |Arc Tangent                |“atan(x)”, arc tangent of the value x                              |
    /// |ceil       |Ceil value                 |“ceil(x)”, value of x rounded up                                   |
    /// |cos        |Cosine                     |“cos(x)”, cosine of the value of x                                 |
    /// |cosh       |Hyperbolic Cosine          |“cosh(x)", hyperbolic cosine of the value x                        |
    /// |deg        |Radiant to Degree convert  |“deg(x)”, the degree value of radiant value x                      |
    /// |exp        |Exponent                   |“exp(x)”, value of constant e raised to the power of x             |
    /// |floor      |Floor value                |“floor(x)”, value of x rounded down                                |
    /// |ln         |Natural logarithm          |“ln(x)”, natural logarithm of x                                    |
    /// |max        |Maximum of two values      |“max(x,y)”, returns x if (x > y) or returns y if (y > x)           |
    /// |min        |Minimum of two values      |“min(x,y)", returns x if (x < y) or returns y if (y < x)           |
    /// |rad        |Degree to Radiant convert  |“rad(x)”, the radiant value of degree value x                      |
    /// |rand       |Random value               |“rand(x)”, returns a random floating point value between 0 and x   |
    /// |sin        |Sine                       |“sin(x)”, sine of the value x                                      |
    /// |sinh       |Hyperbolic Sine            |"sinh(x)”, hyperbolic sine of the value x                          |
    /// |sqrt       |Square root                |“sqrt(x)”, square root of the value x                              |
    /// |tan        |Tangent                    |“tan(x)”, tangent of the value x                                   |
    /// |tanh       |Hyperbolic Tangent         |“tanh(x)", hyperbolic tangent of the value x                       |
    ///
    /// # Xml example
    ///
    /// <p:animcalcmode="lin" valueType="num">
    ///   <p:cBhvr>
    ///     <p:cTn id="9" dur="664" tmFilter="0.0,0.0; 0.25,0.07;0.50,0.2; 0.75,0.467; 1.0,1.0">
    ///       <p:stCondLst>
    ///         <p:cond delay="0"/>
    ///       </p:stCondLst>
    ///     </p:cTn>
    ///     <p:tgtEl>
    ///       <p:spTgtspid="4"/>
    ///     </p:tgtEl>
    ///     <p:attrNameLst>
    ///       <p:attrName>ppt_y</p:attrName>
    ///     </p:attrNameLst>
    ///   </p:cBhvr>
    ///   <p:tavLst>
    ///     <p:tav tm="0%" fmla="#ppt_y-sin(pi*$)/3">
    ///       <p:val>
    ///         <p:fltValval="0.5"/>
    ///       </p:val>
    ///     </p:tav>
    ///     <p:tav tm="100%">
    ///       <p:val>
    ///         <p:fltValval="1"/>
    ///       </p:val>
    ///     </p:tav>
    ///   </p:tavLst>
    /// </p:anim>
    ///
    /// The animation example above modifies the ppt_y variable of the object by subtracting
    /// sin(pi*$)/3 from the non-animated value of ppt_y. The start value is 0.5 and the end
    /// value is 1 specified in each of the val elements. The total time for this animation is
    /// specified within the dur attribute and the filtered time graph is specified by the tmFilter
    /// attribute. The end result is that the object moves from a point above its non-animated
    /// position back to its non-animated position. With the specification of the tmFilter it has a
    /// modified time graph such that it also appears to accelerate as it reaches its final position.
    ///
    /// ## Note
    ///
    /// For this example, the non-animated value of ppt_y is the value of this variable if
    /// the object were to be statically rendered on the slide without animation properties.
    pub formula: Option<String>,
    /// The element specifies a value for a time animate.
    ///
    /// # Xml example
    ///
    /// Consider a shape with a fade in animation effect. The <val> element should be used as follows:
    /// ```xml
    /// <p:anim calcmode="lin" valueType="num">
    ///   <p:cBhvr additive="base"> … </p:cBhvr>
    ///   <p:tavLst>
    ///     <p:tav tm="0%">
    ///       <p:val>
    ///         <p:strVal val="0-#ppt_w/2"/>
    ///       </p:val>
    ///     </p:tav>
    ///     <p:tav tm="100%">
    ///       <p:val>
    ///         <p:strVal val="#ppt_x"/>
    ///       </p:val>
    ///     </p:tav>
    ///   </p:tavLst>
    /// </p:anim>
    /// ```
    pub value: Option<TLAnimVariant>,
}

impl TLTimeAnimateValue {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut instance: Self = Default::default();

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "tm" => instance.time = Some(value.parse()?),
                "fmla" => instance.formula = Some(value.clone()),
                _ => (),
            }
        }

        if let Some(child_node) = xml_node.child_nodes.get(0) {
            let val_node = child_node
                .child_nodes
                .get(0)
                .ok_or_else(|| MissingChildNodeError::new(child_node.name.clone(), "CT_TLAnimVariant"))?;
            instance.value = Some(TLAnimVariant::from_xml_element(val_node)?);
        }

        Ok(instance)
    }
}

#[derive(Debug, Clone)]
pub enum TLTimeAnimateValueTime {
    Percentage(msoffice_shared::drawingml::PositiveFixedPercentage),
    Indefinite,
}

impl FromStr for TLTimeAnimateValueTime {
    type Err = msoffice_shared::error::ParseEnumError;

    fn from_str(s: &str) -> ::std::result::Result<Self, Self::Err> {
        match s {
            "indefinite" => Ok(TLTimeAnimateValueTime::Indefinite),
            _ => Ok(TLTimeAnimateValueTime::Percentage(
                s.parse().map_err(|_| Self::Err::new("TLTimeAnimateValueTime"))?,
            )),
        }
    }
}

#[derive(Debug, Clone)]
pub enum TLAnimVariant {
    /// This element specifies a boolean value to be used for evaluation by a parent element. The exact meaning of the
    /// value contained within this element is not defined here but is dependent on the usage of this element in
    /// conjunction with one of the listed parent elements.
    Bool(bool),
    /// This element specifies an integer value to be used for evaluation by a parent element. The exact meaning of the
    /// value contained within this element is not defined here but is dependent on the usage of this element in
    /// conjunction with one of the listed parent elements.
    Int(i32),
    /// This element specifies a floating point value to be used for evaluation by a parent element. The exact meaning
    /// of the value contained within this element is not defined here but is dependent on the usage of this element in
    /// conjunction with one of the listed parent elements.
    Float(f32),
    /// This element specifies a string value to be used for evaluation by a parent element. The exact meaning of the
    /// value contained within this element is not defined here but is dependent on the usage of this element in
    /// conjunction with one of the listed parent elements.
    String(String),
    /// This element describes the color variant. This is used to specify a color that is to be used for animating the color
    /// property of an object.
    ///
    /// # Xml example
    ///
    /// ```xml
    /// <p:set>
    ///   <p:cBhvr override="childStyle">
    ///    ///   </p:cBhvr>
    ///   <p:to>
    ///     <p:clrVal>
    ///       <a:schemeClr val="accent2"/>
    ///     </p:clrVal>
    ///   </p:to>
    /// </p:set>
    /// ```
    Color(msoffice_shared::drawingml::Color),
}

impl TLAnimVariant {
    pub fn is_choice_member<T>(name: T) -> bool
    where
        T: AsRef<str>,
    {
        match name.as_ref() {
            "boolVal" | "intVal" | "fltVal" | "strVal" | "clrVal" => true,
            _ => false,
        }
    }

    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        match xml_node.local_name() {
            "boolVal" => {
                let val_attr = xml_node
                    .attribute("val")
                    .ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "val"))?;
                Ok(TLAnimVariant::Bool(parse_xml_bool(val_attr)?))
            }
            "intVal" => {
                let val_attr = xml_node
                    .attribute("val")
                    .ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "val"))?;
                Ok(TLAnimVariant::Int(val_attr.parse()?))
            }
            "fltVal" => {
                let val_attr = xml_node
                    .attribute("val")
                    .ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "val"))?;
                Ok(TLAnimVariant::Float(val_attr.parse()?))
            }
            "strVal" => {
                let val_attr = xml_node
                    .attribute("val")
                    .ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "val"))?;
                Ok(TLAnimVariant::String(val_attr.clone()))
            }
            "clrVal" => {
                let child_node = xml_node
                    .child_nodes
                    .get(0)
                    .ok_or_else(|| MissingChildNodeError::new(xml_node.name.clone(), "EG_Color"))?;
                Ok(TLAnimVariant::Color(
                    msoffice_shared::drawingml::Color::from_xml_element(child_node)?,
                ))
            }
            _ => Err(NotGroupMemberError::new(xml_node.name.clone(), "EG_TLAnimVariant").into()),
        }
    }
}

#[derive(Debug, Clone)]
pub enum TLTimeConditionTriggerGroup {
    TargetElement(TLTimeTargetElement),
    /// This element describes the time node trigger choice.
    ///
    /// # Xml example
    ///
    /// Consider a time node with an event condition. The <tn> element should be used as follows:
    /// ```xml
    /// <p:par>
    ///   <p:cTn id="5">
    ///     <p:stCondLst>
    ///       <p:cond delay="0"/>
    ///     </p:stCondLst>
    ///     <p:endCondLst>
    ///       <p:cond evt="begin" delay="0">
    ///         <p:tn val="5"/>
    ///       </p:cond>
    ///     </p:endCondLst>
    ///     <p:childTnLst> … </p:childTnLst>
    ///   </p:cTn>
    /// </p:par>
    /// ```
    TimeNode(TLTimeNodeId),
    /// This element specifies the child time node that triggers a time condition. References a child time node or all
    /// child nodes. Order is based on the child's end time.
    ///
    /// # Xml example
    ///
    /// Consider an animation which ends the synchronization of all parallel time nodes when all the child
    /// nodes have ended their animation. The <rtn> element should be used as follows:
    /// ```xml
    /// <p:cTn>
    ///   <p:stCondLst> … </p:stCondLst>
    ///   <p:endSync evt="end" delay="0">
    ///     <p:rtn val="all"/>
    ///   </p:endSync>
    ///   <p:childTnLst> … </p:childTnLst>
    /// </p:cTn>
    /// ```
    RuntimeNode(TLTriggerRuntimeNode),
}

impl TLTimeConditionTriggerGroup {
    pub fn is_choice_member<T>(name: T) -> bool
    where
        T: AsRef<str>,
    {
        match name.as_ref() {
            "tgtEl" | "tn" | "rtn" => true,
            _ => false,
        }
    }

    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        match xml_node.local_name() {
            "tgtEl" => {
                let target_element_node = xml_node
                    .child_nodes
                    .get(0)
                    .ok_or_else(|| MissingChildNodeError::new(xml_node.name.clone(), "CT_TLTimeTargetElement"))?;
                Ok(TLTimeConditionTriggerGroup::TargetElement(
                    TLTimeTargetElement::from_xml_element(target_element_node)?,
                ))
            }
            "tn" => {
                let val_attr = xml_node
                    .attribute("val")
                    .ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "val"))?;
                Ok(TLTimeConditionTriggerGroup::TimeNode(val_attr.parse()?))
            }
            "rtn" => {
                let val_attr = xml_node
                    .attribute("val")
                    .ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "val"))?;
                Ok(TLTimeConditionTriggerGroup::RuntimeNode(val_attr.parse()?))
            }
            _ => Err(Box::new(NotGroupMemberError::new(
                xml_node.name.clone(),
                "EG_TLTimeConditionTriggerGroup",
            ))),
        }
    }
}

#[derive(Debug, Clone)]
pub enum TLTimeTargetElement {
    /// This element specifies the slide as the target element.
    ///
    /// # Xml example
    ///
    /// For example, suppose we have a simple animation with a blind entrance.
    /// ```xml
    /// <p:seq concurrent="1" nextAc="seek">
    ///   <p:cTn id="2" dur="indefinite" nodeType="mainSeq"> … </p:cTn>
    ///   <p:prevCondLst> … </p:prevCondLst>
    ///   <p:nextCondLst>
    ///     <p:cond evt="onNext" delay="0">
    ///       <p:tgtEl>
    ///         <p:sldTgt/>
    ///       </p:tgtEl>
    ///     </p:cond>
    ///   </p:nextCondLst>
    /// </p:seq>
    /// ```
    SlideTarget,
    /// This element describes the sound information for a target object.
    ///
    /// # Xml example
    ///
    /// Consider a shape with a sound effect animation. The <sndTgt> element should be used as follows:
    /// ```xml
    /// <p:subTnLst>
    ///   <p:audio>
    ///     <p:cMediaNode>
    ///       <p:cTn display="0" masterRel="sameClick"> … </p:cTn>
    ///       <p:tgtEl>
    ///         <p:sndTgt r:embed="rId2" r:link="rId3"/>
    ///       </p:tgtEl>
    ///     </p:cMediaNode>
    ///   </p:audio>
    /// </p:subTnLst>
    /// ```
    SoundTarget(msoffice_shared::drawingml::EmbeddedWAVAudioFile),
    /// The element specifies the shape in which to apply a certain animation to.Err
    ///
    /// # Xml example
    ///
    /// Consider a shape whose id is 3 in which we want to apply a fade animation effect. The <spTgt> should
    /// be used as follows:
    /// ```xml
    /// <p:animEffect transition="in" filter="fade">
    ///   <p:cBhvr>
    ///     <p:cTn id="7" dur="2000"/>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="3"/>
    ///     </p:tgtEl>
    ///   </p:cBhvr>
    /// </p:animEffect>
    /// ```
    ShapeTarget(TLShapeTargetElement),
    /// This element specifies an animation target element that is represented by a sub-shape in a legacy graphical
    /// object.
    ///
    /// # Xml example
    ///
    /// ```xml
    /// <p:animEffect transition="in" filter="blinds(horizontal)">
    ///   <p:cBhvr>
    ///     <p:cTn id="7" dur="500"/>
    ///     <p:tgtEl>
    ///       <p:inkTgt spid="_x0000_s2057"/>
    ///     </p:tgtEl>
    ///   </p:cBhvr>
    /// </p:animEffect>
    /// ```
    InkTarget(TLSubShapeId),
}

impl TLTimeTargetElement {
    pub fn is_choice_member<T>(name: T) -> bool
    where
        T: AsRef<str>,
    {
        match name.as_ref() {
            "sldTgt" | "sndTgt" | "spTgt" | "inkTgt" => true,
            _ => false,
        }
    }

    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        match xml_node.local_name() {
            "sldTgt" => Ok(TLTimeTargetElement::SlideTarget),
            "sndTgt" => Ok(TLTimeTargetElement::SoundTarget(
                msoffice_shared::drawingml::EmbeddedWAVAudioFile::from_xml_element(xml_node)?,
            )),
            "spTgt" => {
                let child_node = xml_node
                    .child_nodes
                    .get(0)
                    .ok_or_else(|| MissingChildNodeError::new(xml_node.name.clone(), "CT_TLShapeTargetElement"))?;

                Ok(TLTimeTargetElement::ShapeTarget(
                    TLShapeTargetElement::from_xml_element(child_node)?,
                ))
            }
            "inkTgt" => {
                let spid_attr = xml_node
                    .attribute("spid")
                    .ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "spid"))?;

                Ok(TLTimeTargetElement::InkTarget(spid_attr.parse()?))
            }
            _ => Err(Box::new(NotGroupMemberError::new(
                xml_node.name.clone(),
                "CT_TLTimeTargetElement",
            ))),
        }
    }
}

#[derive(Debug, Clone)]
pub struct TLShapeTargetElement {
    /// This attribute specifies the shape identifier.
    pub shape_id: msoffice_shared::drawingml::DrawingElementId,
    pub target: Option<TLShapeTargetElementGroup>,
}

impl TLShapeTargetElement {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let shape_id_attr = xml_node
            .attribute("spid")
            .ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "spid"))?;
        let shape_id = shape_id_attr.parse()?;

        let target = match xml_node.child_nodes.get(0) {
            Some(child_node) => Some(TLShapeTargetElementGroup::from_xml_element(child_node)?),
            None => None,
        };

        Ok(Self { shape_id, target })
    }
}

#[derive(Debug, Clone)]
pub enum TLShapeTargetElementGroup {
    /// This element is used to specify animating the background of an object.
    ///
    /// # Xml example
    ///
    /// Consider adding animation to the background of Shape Id 3. The <bg> tag can be used as follows:
    ///
    /// ```xml
    /// <p:tgtEl>
    ///   <p:spTgt spid="3">
    ///     <p:bg/>
    ///   </p:spTgt>
    /// </p:tgtEl>
    /// ```
    Background,
    /// This element specifies the subshape of a legacy graphical object to animate.
    ///
    /// # Xml example
    ///
    /// Consider adding animation to a legacy diagram. The <subSp> element should be used as follows:
    /// ```xml
    /// <p:animEffect transition="in" filter="blinds(horizontal)">
    ///   <p:cBhvr>
    ///     <p:cTn id="7" dur="500"/>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="2053">
    ///         <p:subSp spid="_x0000_s70664"/>
    ///       </p:spTgt>
    ///     </p:tgtEl>
    ///   </p:cBhvr>
    /// </p:animEffect>
    /// ```
    SubShape(TLSubShapeId),
    /// This element specifies the subelement of an embedded chart to animate.
    ///
    /// # Xml example
    ///
    /// Consider an embedded Chart with a entrance animation effect applied to each of the graph's
    /// categories. The <oldChartEl> element should be used as follows:
    /// ```xml
    /// <p:animEffect transition="in" filter="blinds(horizontal)">
    ///   <p:cBhvr>
    ///     <p:cTn id="12" dur="500"/>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="19460">
    ///         <p:oleChartEl type="category" lvl="1"/>
    ///       </p:spTgt>
    ///     </p:tgtEl>
    ///   </p:cBhvr>
    /// </p:animEffect>
    /// ```
    OleChartElement(TLOleChartTargetElement),
    /// This element specifies a text element to animate.
    ///
    /// # Xml example
    ///
    /// Consider a shape containing text to be animated. The <txEl> should be used as follows:
    /// ```xml
    /// <p:tgtEl>
    ///   <p:spTgt spid="5">
    ///     <p:txEl>
    ///       <p:pRg st="1" end="1"/>
    ///     </p:txEl>
    ///   </p:spTgt>
    /// </p:tgtEl>
    /// ```
    TextElement(Option<TLTextTargetElement>),
    /// This element specifies a graphical element which to animate
    ///
    /// # Xml example
    ///
    /// ```xml
    /// <p:set>
    ///   <p:cBhvr>
    ///     <p:cTn id="6" dur="1" fill="hold"> … </p:cTn>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="4">
    ///         <p:graphicEl>
    ///           <a:dgm id="{87C2C707-C3F4-4E81-A967-A8B8AE13E575}"/>
    ///         </p:graphicEl>
    ///       </p:spTgt>
    ///     </p:tgtEl>
    ///     <p:attrNameLst> … </p:attrNameLst>
    ///   </p:cBhvr>
    ///   <p:to> … </p:to>
    /// </p:set>
    /// ```
    GraphicElement(msoffice_shared::drawingml::AnimationElementChoice),
}

impl TLShapeTargetElementGroup {
    pub fn is_choice_member<T>(name: T) -> bool
    where
        T: AsRef<str>,
    {
        match name.as_ref() {
            "bg" | "subSp" | "oleChartEl" | "txEl" | "graphicEl" => true,
            _ => false,
        }
    }

    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        match xml_node.local_name() {
            "bg" => Ok(TLShapeTargetElementGroup::Background),
            "subSp" => {
                let spid_attr = xml_node
                    .attribute("spid")
                    .ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "spid"))?;

                Ok(TLShapeTargetElementGroup::SubShape(spid_attr.parse()?))
            }
            "oleChartEl" => Ok(TLShapeTargetElementGroup::OleChartElement(
                TLOleChartTargetElement::from_xml_element(xml_node)?,
            )),
            "txEl" => Ok(TLShapeTargetElementGroup::TextElement(
                match xml_node.child_nodes.get(0) {
                    Some(child_node) => Some(TLTextTargetElement::from_xml_element(child_node)?),
                    None => None,
                },
            )),
            "graphicEl" => {
                let child_node = xml_node
                    .child_nodes
                    .get(0)
                    .ok_or_else(|| MissingChildNodeError::new(xml_node.name.clone(), "CT_AnimationElementChoice"))?;

                Ok(TLShapeTargetElementGroup::GraphicElement(
                    msoffice_shared::drawingml::AnimationElementChoice::from_xml_element(child_node)?,
                ))
            }
            _ => Err(Box::new(NotGroupMemberError::new(
                xml_node.name.clone(),
                "TLShapeTargetElementGroup",
            ))),
        }
    }
}

#[derive(Debug, Clone)]
pub struct TLOleChartTargetElement {
    /// This attribute specifies how to chart should be built during its animation.
    pub element_type: TLChartSubelementType,
    /// This attribute describes the element levels to animate.
    ///
    /// Defaults to 0
    pub level: Option<u32>,
}

impl TLOleChartTargetElement {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut element_type = None;
        let mut level = None;

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "type" => element_type = Some(value.parse()?),
                "lvl" => level = Some(value.parse()?),
                _ => (),
            }
        }

        let element_type = element_type.ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "type"))?;

        Ok(Self { element_type, level })
    }
}

#[derive(Debug, Clone)]
pub enum TLTextTargetElement {
    /// This element specifies animation on a character range defined by a start and end character position.
    ///
    /// # Xml example
    ///
    /// ```xml
    /// <p:animMotion>
    ///   <p:cBhvr>
    ///     <p:cTn id="6" dur="2000" fill="hold"/>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="3">
    ///         <p:txEl>
    ///           <p:charRg st="0" end="9"/>
    ///         </p:txEl>
    ///       </p:spTgt>
    ///     </p:tgtEl>
    ///     <p:attrNameLst>
    ///       <p:attrName>ppt_x</p:attrName>
    ///       <p:attrName>ppt_y</p:attrName>
    ///     </p:attrNameLst>
    ///   </p:cBhvr>
    /// </p:animMotion>
    /// ```
    CharRange(IndexRange),
    /// This element specifies a text range to animate based on starting and ending paragraph number.
    ///
    /// # Xml example
    ///
    /// Consider an animation entrance of the first 3 text paragraphs. The <pRg> element should be used as
    /// follows:
    /// ```xml
    /// <p:animEffect transition="in" filter="checkerboard(across)">
    ///   <p:cBhvr>
    ///     <p:cTn id="12" dur="500"/>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="3">
    ///         <p:txEl>
    ///           <p:pRg st="0" end="2"/>
    ///         </p:txEl>
    ///       </p:spTgt>
    ///     </p:tgtEl>
    ///   </p:cBhvr>
    /// </p:animEffect>
    /// ```
    ParagraphRange(IndexRange),
}

impl TLTextTargetElement {
    pub fn is_choice_member<T>(name: T) -> bool
    where
        T: AsRef<str>,
    {
        match name.as_ref() {
            "charRg" | "pRg" => true,
            _ => false,
        }
    }

    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        match xml_node.local_name() {
            "charRg" => Ok(TLTextTargetElement::CharRange(IndexRange::from_xml_element(xml_node)?)),
            "pRg" => Ok(TLTextTargetElement::ParagraphRange(IndexRange::from_xml_element(
                xml_node,
            )?)),
            _ => Err(Box::new(NotGroupMemberError::new(
                xml_node.name.clone(),
                "TLTextTargetElement",
            ))),
        }
    }
}

/// This element specifies conditions on time nodes in a timeline. It is used within a list of start condition or list of
/// end condition elements.
///
/// # Xml example
///
/// ```xml
/// <p:cTn>
///   <p:stCondLst>
///     <p:cond delay="2000"/>
///   </p:stCondLst>
///   <p:childTnLst>
///     <p:set> … </p:set>
///     <p:animEffect transition="in" filter="blinds(horizontal)">
///       <p:cBhvr>
///         <p:cTn id="7" dur="1000"/>
///         <p:tgtEl>
///           <p:spTgt spid="4"/>
///         </p:tgtEl>
///       </p:cBhvr>
///     </p:animEffect>
///   </p:childTnLst>
/// </p:cTn>
/// ```
#[derive(Default, Debug, Clone)]
pub struct TLTimeCondition {
    /// This attribute describes the event that triggers an animation.
    pub trigger_event: Option<TLTriggerEvent>,
    /// This attribute describes the delay after an animation is triggered.
    pub delay: Option<TLTime>,
    pub trigger: Option<TLTimeConditionTriggerGroup>,
}

impl TLTimeCondition {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut instance: Self = Default::default();

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "evt" => instance.trigger_event = Some(value.parse()?),
                "delay" => instance.delay = Some(value.parse()?),
                _ => (),
            }
        }

        if let Some(child_node) = xml_node.child_nodes.get(0) {
            instance.trigger = Some(TLTimeConditionTriggerGroup::from_xml_element(child_node)?);
        }

        Ok(instance)
    }
}

/// This element describes the properties that are common for time nodes.
#[derive(Default, Debug, Clone)]
pub struct TLCommonTimeNodeData {
    /// This attribute specifies the identifier for the timenode.
    pub id: Option<TLTimeNodeId>,
    /// This attribute describes the preset identifier for the time node.
    pub preset_id: Option<i32>,
    /// This attribute descries the class of effect in which it belongs.
    pub preset_class: Option<TLTimeNodePresetClassType>,
    /// This attribute is a bitflag that specifies a direction or some other attribute of the effect.
    /// For example it can be set to specify a “From Bottom” for the Fly In effect, or “Bold” for
    /// the Change Font Style effect.
    pub preset_subtype: Option<i32>,
    /// This attribute describes the duration of the time node, expressed as unit time.
    pub duration: Option<TLTime>,
    /// This attribute describes the number of times the element should repeat, in units of
    /// thousandths.
    ///
    /// Defaults to 100_0
    pub repeat_count: Option<TLTime>,
    /// This attribute describes the amount of time over which the element should repeat. If
    /// absent, the attribute is taken to be the same as the specified duration.
    pub repeat_duration: Option<TLTime>,
    /// This attribute specifies the percentage by which to speed up (or slow down) the timing. If
    /// negative, the timing is reversed.
    ///
    /// Defaults to 100_000
    ///
    /// # Example
    ///
    /// If speed is 200% (200_000) and the specified duration is 10 seconds, the actual duration is 5 seconds.
    pub speed: Option<msoffice_shared::drawingml::Percentage>,
    /// This attribute describes the percentage of specified duration over which the element's
    /// time takes to accelerate from 0 up to the "run rate."
    ///
    /// Defaults to 0
    pub acceleration: Option<msoffice_shared::drawingml::PositiveFixedPercentage>,
    /// This attribute describes the percentage of specified duration over which the element's
    /// time takes to decelerate from the "run rate" down to 0.
    ///
    /// Defaults to 0
    pub deceleration: Option<msoffice_shared::drawingml::PositiveFixedPercentage>,
    /// This attribute describes whether to automatically play the animation in reverse after
    /// playing it in the forward direction.
    ///
    /// Defaults to false
    pub auto_reverse: Option<bool>,
    /// This attribute specifies if a node is to restart when it completes its action
    pub restart_type: Option<TLTimeNodeRestartType>,
    /// This attribute describes the fill type for the time node.
    pub fill_type: Option<TLTimeNodeFillType>,
    /// This attribute specifies how the time node synchronizes to its group.
    pub sync_behavior: Option<TLTimeNodeSyncType>,
    /// This attribute specifies the time filter for the time node.
    pub time_filter: Option<String>,
    /// This attribute describes the event filter for this time node.
    pub event_filter: Option<String>,
    /// This attribute describes whether the state of the time node is visible or hidden.
    pub display: Option<bool>,
    /// This attribute specifies how the time node plays back relative to its master time node.
    pub master_relationship: Option<TLTimeNodeMasterRelation>,
    /// This attribute describes the build level of the animation.
    pub build_level: Option<i32>,
    /// This attribute describes the Group ID of the time node.
    pub group_id: Option<u32>,
    /// This attribute specifies whether there is an after effect applied to the time node.
    pub after_effect: Option<bool>,
    /// This attribute specifies the type of time node.
    pub node_type: Option<TLTimeNodeType>,
    /// This attribute describes whether this node is a placeholder.
    pub node_placeholder: Option<bool>,
    /// This element contains a list conditions that shall be met for a time node to be activated.
    ///
    /// # Xml example
    ///
    /// example, suppose we have a shape with an entrance appearance after 5 seconds. The
    /// <stCondLst> element should be used as follows:
    /// ```xml
    /// <p:par>
    ///   <p:cTn id="5" nodeType="clickEffect">
    ///     <p:stCondLst>
    ///       <p:cond delay="5000"/>
    ///     </p:stCondLst>
    ///     <p:childTnLst> … </p:childTnLst>
    ///   </p:cTn>
    /// </p:par>
    /// ```
    pub start_condition_list: Option<Vec<TLTimeCondition>>,
    /// This element describes a list of the end conditions that shall be met in order to stop the time node.
    ///
    /// # Xml example
    ///
    /// Consider a shape a shape with an audio attached to the animation. The <endCondList> element
    /// should be used as follows to specifies when the sound is done:
    /// ```xml
    /// <p:audio>
    ///   <p:cMediaNode>
    ///     <p:cTn display="0" masterRel="sameClick">
    ///       <p:stCondLst> … </p:stCondLst>
    ///       <p:endCondLst>
    ///         <p:cond evt="onStopAudio" delay="0">
    ///           <p:tgtEl>
    ///             <p:sldTgt/>
    ///           </p:tgtEl>
    ///         </p:cond>
    ///       </p:endCondLst>
    ///     </p:cTn>
    ///     <p:tgtEl> … </p:tgtEl>
    ///   </p:cMediaNode>
    /// </p:audio>
    /// ```
    pub end_condition_list: Option<Vec<TLTimeCondition>>,
    /// This element is used to synchronizes the stopping of parallel elements in the timing tree. It is used on interactive
    /// timeline sequences to specify that the interactive sequence’s duration ends when all of the child timenodes
    /// have ended. It is also used to make interactive sequences restart-able (so that the entire interactive sequence
    /// can be repeated if the trigger object is clicked on repeatedly).
    ///
    /// # Xml example
    ///
    /// ```xml
    /// <p:seq concurrent="1" nextAc="seek">
    ///   <p:cTn>
    ///     <p:stCondLst/>
    ///     <p:endSync evt="end" delay="0">
    ///       <p:rtn val="all"/>
    ///     </p:endSync>
    ///     <p:childTnLst/>
    ///   </p:cTn>
    ///   <p:nextCondLst/>
    /// </p:seq>
    /// ```
    pub end_sync: Option<TLTimeCondition>,
    /// This element specifies how the animation should be successively applied to sub elements of the target element
    /// for a repeated effect. It can be applied to contained timing and animation structures over the letters, words, or
    /// shapes within a target element.
    ///
    /// # Xml example
    ///
    /// Consider a text animation where the words appear letter by letter. The <iterate> element should be
    /// used as follows:
    /// ```xml
    /// <p:par>
    ///   <p:cTn id="1" >
    ///     <p:stCondLst> … </p:stCondLst>
    ///     <p:iterate type="lt">
    ///       <p:tmPct val="10000"/>
    ///     </p:iterate>
    ///     <p:childTnLst> … </p:childTnLst>
    ///   </p:cTn>
    /// </p:par>
    /// ```
    pub iterate: Option<TLIterateData>,
    /// This element describes the list of time nodes that have a fixed location in the timing tree based on their parent
    /// time node. The children's start time is defined relative to their parent time node’s start.
    pub child_time_node_list: Option<Vec<TimeNodeGroup>>,
    /// This element describes time nodes that have a start time which is not based on the containing timenode. It is
    /// instead based on their master relationship (masterRel). At runtime, they are inserted dynamically into the
    /// timing tree as child timenodes for playback, based on the logic defined by the master relationship. These
    /// elements are used for animations such as "dim after" and "play sound effects"
    ///
    /// # Xml example
    ///
    /// Consider an animation with a "Fly In" effect on paragraphs so that each paragraph flies in on a
    /// separate click. Then the "Dim After" effect for paragraph 1 doe not happen until paragraph 2 flies in. The
    /// <subTnLst> element should be used as follows:
    /// ```xml
    /// <p:par>
    ///   <p:cTn id="5" grpId="0" nodeType="clickEffect">
    ///     <p:stCondLst> … </p:stCondLst>
    ///     <p:childTnLst> … </p:childTnLst>
    ///     <p:subTnLst>
    ///       <p:set>
    ///         <p:cBhvr override="childStyle">
    ///           <p:cTn fill="hold" masterRel="nextClick" afterEffect="1"/>
    ///           <p:tgtEl> … </p:tgtEl>
    ///           <p:attrNameLst> … </p:attrNameLst>
    ///         </p:cBhvr>
    ///         <p:to> … </p:to>
    ///         </p:set>
    ///     </p:subTnLst>
    ///   </p:cTn>
    /// </p:par>
    /// ```
    pub sub_time_node_list: Option<Vec<TimeNodeGroup>>,
}

impl TLCommonTimeNodeData {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut instance: Self = Default::default();

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "id" => instance.id = Some(value.parse()?),
                "presetID" => instance.preset_id = Some(value.parse()?),
                "presetClass" => instance.preset_class = Some(value.parse()?),
                "presetSubtype" => instance.preset_subtype = Some(value.parse()?),
                "dur" => instance.duration = Some(value.parse()?),
                "repeatCount" => instance.repeat_count = Some(value.parse()?),
                "repeatDur" => instance.repeat_duration = Some(value.parse()?),
                "spd" => instance.speed = Some(value.parse()?),
                "accel" => instance.acceleration = Some(value.parse()?),
                "decel" => instance.deceleration = Some(value.parse()?),
                "autoRev" => instance.auto_reverse = Some(parse_xml_bool(value)?),
                "restart" => instance.restart_type = Some(value.parse()?),
                "fill" => instance.fill_type = Some(value.parse()?),
                "syncBehavior" => instance.sync_behavior = Some(value.parse()?),
                "tmFilter" => instance.time_filter = Some(value.clone()),
                "evtFilter" => instance.event_filter = Some(value.clone()),
                "display" => instance.display = Some(parse_xml_bool(value)?),
                "masterRel" => instance.master_relationship = Some(value.parse()?),
                "bldLvl" => instance.build_level = Some(value.parse()?),
                "grpId" => instance.group_id = Some(value.parse()?),
                "afterEffect" => instance.after_effect = Some(parse_xml_bool(value)?),
                "nodeType" => instance.node_type = Some(value.parse()?),
                "nodePh" => instance.node_placeholder = Some(parse_xml_bool(value)?),
                _ => (),
            }
        }

        for child_node in &xml_node.child_nodes {
            match child_node.local_name() {
                "stCondLst" => {
                    let mut vec = Vec::new();
                    for cond_node in &child_node.child_nodes {
                        vec.push(TLTimeCondition::from_xml_element(cond_node)?);
                    }

                    if vec.is_empty() {
                        return Err(Box::new(MissingChildNodeError::new(child_node.name.clone(), "cond")));
                    }

                    instance.start_condition_list = Some(vec);
                }
                "endCondLst" => {
                    let mut vec = Vec::new();
                    for cond_node in &child_node.child_nodes {
                        vec.push(TLTimeCondition::from_xml_element(cond_node)?);
                    }

                    if vec.is_empty() {
                        return Err(Box::new(MissingChildNodeError::new(child_node.name.clone(), "cond")));
                    }

                    instance.end_condition_list = Some(vec);
                }
                "endSync" => instance.end_sync = Some(TLTimeCondition::from_xml_element(child_node)?),
                "iterate" => instance.iterate = Some(TLIterateData::from_xml_element(child_node)?),
                "childTnLst" => {
                    let mut vec = Vec::new();
                    for time_node in &child_node.child_nodes {
                        vec.push(TimeNodeGroup::from_xml_element(time_node)?);
                    }

                    if vec.is_empty() {
                        return Err(Box::new(MissingChildNodeError::new(
                            child_node.name.clone(),
                            "TimeNode",
                        )));
                    }

                    instance.child_time_node_list = Some(vec);
                }
                "subTnLst" => {
                    let mut vec = Vec::new();
                    for time_node in &child_node.child_nodes {
                        vec.push(TimeNodeGroup::from_xml_element(time_node)?);
                    }

                    if vec.is_empty() {
                        return Err(Box::new(MissingChildNodeError::new(
                            child_node.name.clone(),
                            "TimeNode",
                        )));
                    }

                    instance.sub_time_node_list = Some(vec);
                }
                _ => (),
            }
        }

        Ok(instance)
    }
}

#[derive(Debug, Clone)]
pub enum TLIterateDataChoice {
    /// This element describes the duration of the iteration interval in absolute time.
    ///
    /// # Xml example
    ///
    /// Consider a text animation where the words appear letter by letter every 10 seconds. The <tmAbs>
    /// element should be used as follows:
    /// ```xml
    /// <p:par>
    ///   <p:cTn id="5" >
    ///     <p:stCondLst> … </p:stCondLst>
    ///     <p:iterate type="lt">
    ///       <p:tmAbs val="10000"/>
    ///     </p:iterate>
    ///     <p:childTnLst> … </p:childTnLst>
    ///   </p:cTn>
    /// </p:par>
    /// ```
    Absolute(TLTime),
    /// This element describes the duration of the iteration interval in a percentage of time.
    ///
    /// # Xml example
    ///
    /// Consider a text animation where the words appear letter by letter every 10th of the animation
    /// duration. The <tmPct> element should be used as follows:
    /// ```xml
    /// <p:par>
    ///   <p:cTn id="5">
    ///     <p:stCondLst> … </p:stCondLst>
    ///     <p:iterate type="lt">
    ///       <p:tmPct val="10%"/>
    ///     </p:iterate>
    ///     <p:childTnLst> … </p:childTnLst>
    ///   </p:cTn>
    /// </p:par>
    /// ```
    Percent(msoffice_shared::drawingml::PositivePercentage),
}

impl TLIterateDataChoice {
    pub fn is_choice_member<T>(name: T) -> bool
    where
        T: AsRef<str>,
    {
        match name.as_ref() {
            "tmAbs" | "tmPct" => true,
            _ => false,
        }
    }

    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        match xml_node.local_name() {
            "tmAbs" => {
                let val_attr = xml_node
                    .attribute("val")
                    .ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "val"))?;
                Ok(TLIterateDataChoice::Absolute(val_attr.parse()?))
            }
            "tmPct" => {
                let val_attr = xml_node
                    .attribute("val")
                    .ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "val"))?;
                Ok(TLIterateDataChoice::Percent(val_attr.parse()?))
            }
            _ => Err(Box::new(NotGroupMemberError::new(
                xml_node.name.clone(),
                "TLIterateDataChoice",
            ))),
        }
    }
}

#[derive(Debug, Clone)]
pub struct TLIterateData {
    /// This attribute specifies the iteration behavior and applies it to each letter, word or shape
    /// within a container element.
    ///
    /// Values are by word, by letter, or by element. If there is no text or block elements such as
    /// shapes within the container or a single word, letter, or shape (depending on iterate type)
    /// then no iteration happens and the behavior is applied to the element itself instead.
    ///
    /// Defaults to IterateType::Element
    pub iterate_type: Option<IterateType>,
    /// This attribute specifies whether to go backwards in the timeline to the previous node.
    ///
    /// Defaults to false
    pub backwards: Option<bool>,
    pub interval: TLIterateDataChoice,
}

impl TLIterateData {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut iterate_type = None;
        let mut backwards = None;

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "type" => iterate_type = Some(value.parse()?),
                "backwards" => backwards = Some(parse_xml_bool(value)?),
                _ => (),
            }
        }

        let interval_node = xml_node
            .child_nodes
            .get(0)
            .ok_or_else(|| MissingChildNodeError::new(xml_node.name.clone(), "TLIterateDataChoice"))?;
        let interval = TLIterateDataChoice::from_xml_element(interval_node)?;

        Ok(Self {
            iterate_type,
            backwards,
            interval,
        })
    }
}

#[derive(Debug, Clone)]
pub enum TLByAnimateColorTransform {
    /// The element specifies an incremental RGB value to add to the color property
    ///
    /// # Xml example
    ///
    /// ```xml
    /// <p:animClr clrSpc="rgb">
    ///   <p:cBhvr>
    ///     <p:cTn id="8" dur="500" fill="hold"/>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="4"/>
    ///     </p:tgtEl>
    ///     <p:attrNameLst>
    ///       <p:attrName>stroke.color</p:attrName>
    ///     </p:attrNameLst>
    ///   </p:cBhvr>
    ///   <p:by>
    ///     <p:rgb r="10" g="20" b="30"/>
    ///   </p:by>
    /// </p:animClr>
    /// ```
    Rgb(TLByRgbColorTransform),
    /// This element specifies an incremental HSL (Hue, Saturation, Lightness) value to add to a color animation.
    ///
    /// # Xml example
    ///
    /// ```xml
    /// <p:animClr clrSpc="hsl">
    ///   <p:cBhvr>
    ///     <p:cTn id="8" dur="500" fill="hold"/>
    ///     <p:tgtEl>
    ///       <p:spTgt spid="4"/>
    ///     </p:tgtEl>
    ///     <p:attrNameLst>
    ///       <p:attrName>stroke.color</p:attrName>
    ///     </p:attrNameLst>
    ///   </p:cBhvr>
    ///   <p:by>
    ///     <p:hsl h="0" s="0" l="0"/>
    ///   </p:by>
    /// </p:animClr>
    /// ```
    Hsl(TLByHslColorTransform),
}

impl TLByAnimateColorTransform {
    pub fn is_choice_member<T>(name: T) -> bool
    where
        T: AsRef<str>,
    {
        match name.as_ref() {
            "rgb" | "hsl" => true,
            _ => false,
        }
    }

    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        match xml_node.local_name() {
            "rgb" => Ok(TLByAnimateColorTransform::Rgb(TLByRgbColorTransform::from_xml_element(
                xml_node,
            )?)),
            "hsl" => Ok(TLByAnimateColorTransform::Hsl(TLByHslColorTransform::from_xml_element(
                xml_node,
            )?)),
            _ => Err(Box::new(NotGroupMemberError::new(
                xml_node.name.clone(),
                "TLByAnimateColorTransform",
            ))),
        }
    }
}

#[derive(Debug, Clone)]
pub struct TLByRgbColorTransform {
    /// This attribute specifies a red component luminance as a percentage. Values are in the range [-100%, 100%].
    pub r: msoffice_shared::drawingml::FixedPercentage,
    /// This attribute specifies a green component luminance as a percentage. Values are in the range [-100%, 100%].
    pub g: msoffice_shared::drawingml::FixedPercentage,
    /// This attribute specifies a blue component luminance as a percentage. Values are in the range [-100%, 100%].
    pub b: msoffice_shared::drawingml::FixedPercentage,
}

impl TLByRgbColorTransform {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut r = None;
        let mut g = None;
        let mut b = None;

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "r" => r = Some(value.parse()?),
                "g" => g = Some(value.parse()?),
                "b" => b = Some(value.parse()?),
                _ => (),
            }
        }

        let r = r.ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "r"))?;
        let g = g.ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "g"))?;
        let b = b.ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "b"))?;

        Ok(Self { r, g, b })
    }
}

#[derive(Debug, Clone)]
pub struct TLByHslColorTransform {
    /// Specifies hue as an angle. The values range from [0, 360] degrees
    pub h: msoffice_shared::drawingml::Angle,
    /// Specifies a lightness as a percentage. The values are in the range [-100%, 100%].
    pub s: msoffice_shared::drawingml::FixedPercentage,
    /// Specifies a saturation as a percentage. The values are in the range [-100%, 100%].
    pub l: msoffice_shared::drawingml::FixedPercentage,
}

impl TLByHslColorTransform {
    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        let mut h = None;
        let mut s = None;
        let mut l = None;

        for (attr, value) in &xml_node.attributes {
            match attr.as_str() {
                "h" => h = Some(value.parse()?),
                "s" => s = Some(value.parse()?),
                "l" => l = Some(value.parse()?),
                _ => (),
            }
        }

        let h = h.ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "h"))?;
        let s = s.ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "s"))?;
        let l = l.ok_or_else(|| MissingAttributeError::new(xml_node.name.clone(), "l"))?;

        Ok(Self { h, s, l })
    }
}

#[derive(Debug, Clone)]
pub enum Build {
    /// This element specifies how to build paragraph level properties.
    ///
    /// # Xml example
    ///
    /// Consider having animation applied only to 1st level paragraphs. The <bldP> element should be used
    /// as follows:
    ///
    /// ```xml
    /// <p:bldLst>
    ///   <p:bldP spid="3" grpId="0" build="p"/>
    /// </p:bldLst>
    /// ```
    Paragraph(Box<TLBuildParagraph>),
    /// This element specifies how to build the animation for a diagram.
    ///
    /// # Xml example
    ///
    /// Consider the following example where a chart is specified to be animated by category rather than as
    /// one entity. Thus, the bldChart element should be used as follows:
    ///
    /// ```xml
    /// <p:bdldLst>
    ///   <p:bldGraphic spid="4" grpId="0">
    ///     <p:bldSub>
    ///       <a:bldChart bld="category"/>
    ///     </p:bldSub>
    ///   </p:bldGraphic>
    /// </p:bldLst>
    /// ```
    Diagram(Box<TLBuildDiagram>),
    /// This element describes animation an a embedded Chart.
    ///
    /// # Xml example
    ///
    /// Consider displaying animation on a embedded graphical chart. The <bldOleChart>element should be
    /// use as follows:
    ///
    /// ```xml
    /// <p:bldLst>
    ///   <p:bldOleChart spid="1025" grpId="0"/>
    /// </p:bldLst>
    /// ```
    OleChart(Box<TLOleBuildChart>),
    /// This element specifies how to build a graphical element.
    ///
    /// # Xml example
    ///
    /// Consider having a chart graphical element appear as a whole as opposed to by a category. The
    /// <bldGraphic> element should be used as follows:
    ///
    /// ```xml
    /// <p:bldLdst>
    ///   <p:bldGraphic spid="3" grpId="0">
    ///     <p:bldSub>
    ///       <a:bldChart bld="category"/>
    ///     </p:bldSub>
    ///   </p:bldGraphic>
    /// </p:bldLst>
    /// ```
    Graphic(Box<TLGraphicalObjectBuild>),
}

impl Build {
    pub fn is_choice_member<T>(name: T) -> bool
    where
        T: AsRef<str>,
    {
        match name.as_ref() {
            "bldP" | "bldDgm" | "bldOleChart" | "bldGraphic" => true,
            _ => false,
        }
    }

    pub fn from_xml_element(xml_node: &XmlNode) -> Result<Self> {
        match xml_node.local_name() {
            "bldP" => Ok(Build::Paragraph(Box::new(TLBuildParagraph::from_xml_element(
                xml_node,
            )?))),
            "bldDgm" => Ok(Build::Diagram(Box::new(TLBuildDiagram::from_xml_element(xml_node)?))),
            "bldOleChart" => Ok(Build::OleChart(Box::new(TLOleBuildChart::from_xml_element(xml_node)?))),
            "bldGraphic" => Ok(Build::Graphic(Box::new(TLGraphicalObjectBuild::from_xml_element(
                xml_node,
            )?))),
            _ => Err(Box::new(NotGroupMemberError::new(
                xml_node.name.clone(),
                "CT_BuildList",
            ))),
        }
    }
}