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
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
/* This Source Code Form is subject to the terms of the Mozilla Public
   License, v. 2.0. If a copy of the MPL was not distributed with this
   file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/

//! Backblaze B2 API calls for working with files.
//!
//! See [the B2 documentation on uploading
//! files](https://www.backblaze.com/b2/docs/uploading.html) for an overview of
//! the process.
//!
//!
//! # Uploading Files
//!
//! For files larger than 5 GB, see [Uploading Large
//! Files](#uploading-large-files).
//!
//! To upload a file:
//!
//! 1. Authenticate with B2 to obtain an [Authorization] object.
//! 2. Create an [UploadFile] request.
//! 3. Call [get_upload_authorization] to get an [UploadAuthorization] for a
//!    bucket.
//! 4. Call [upload_file] with your `UploadAuthorization`, `UploadFile` request,
//!    and file data.
//!
//! You can upload multiple files with a single `UploadAuthorization`, but only
//! one at a time. To upload multiple files in parallel, each thread or task
//! needs to obtain its own `UploadAuthorization`.
//!
//!
//! # Uploading Large Files
//!
//! To upload a large file:
//!
//! 1. Authenticate with B2 to obtain an [Authorization] object.
//! 2. Create a [StartLargeFile] object with the destination bucket and new
//!    file's information, then pass it to [start_large_file]. You will receive
//!    a [File] object.
//! 3. Pass the [File] to [get_upload_part_authorization] to receive an
//!    [UploadPartAuthorization].
//!     * You can upload parts in separate threads for better performance; each
//!       thread must call [get_upload_part_authorization] and use its
//!       respective authorization when uploading data.
//! 4. Create an [UploadFilePart] object via the [UploadFilePartBuilder].
//! 5. Use the `UploadPartAuthorization` and `UploadFilePart` to call
//!    [upload_file_part] with the file data to upload.
//! 6. Call [UploadFilePart::create_next_part] to create a new upload part
//!    request.
//! 7. Repeat steps 5 and 6 until all parts have been uploaded.
//! 8. Call [finish_large_file_upload] to merge the file parts into a single
//!    [File]. After finishing the file, it can be treated like any other
//!    uploaded file.
//!
//! # Examples
//!
//! ```no_run
//! # fn calculate_sha1(data: &[u8]) -> String { String::default() }
//! use std::env;
//! use anyhow;
//! use b2_client::{self as b2, HttpClient as _};
//!
//! # #[cfg(feature = "with_surf")]
//! async fn upload_file(name: &str, bucket: b2::Bucket, data: &[u8])
//! -> anyhow::Result<b2::File> {
//!     let key = env::var("B2_KEY").ok().unwrap();
//!     let key_id = env::var("B2_KEY_ID").ok().unwrap();
//!
//!     let client = b2::client::SurfClient::default();
//!     let mut auth = b2::authorize_account(client, &key, &key_id).await?;
//!
//!     let mut upload_auth = b2::get_upload_authorization(&mut auth, &bucket)
//!         .await?;
//!
//!     let checksum = calculate_sha1(&data);
//!
//!     let file = b2::UploadFile::builder()
//!         .file_name(name)?
//!         .sha1_checksum(&checksum)
//!         .build()?;
//!
//!     Ok(b2::upload_file(&mut upload_auth, file, &data).await?)
//! }
//! ```
//!
//! ```no_run
//! # fn calculate_sha1(data: &[u8]) -> String { String::default() }
//! use std::env;
//! use anyhow;
//! use b2_client::{self as b2, HttpClient as _};
//!
//! # #[cfg(feature = "with_surf")]
//! async fn upload_large_file(
//!     name: &str,
//!     data_part1: &[u8],
//!     data_part2: &[u8],
//! ) -> anyhow::Result<b2::File> {
//!     let key = env::var("B2_KEY").ok().unwrap();
//!     let key_id = env::var("B2_KEY_ID").ok().unwrap();
//!
//!     let client = b2::client::SurfClient::default();
//!     let mut auth = b2::authorize_account(client, &key, &key_id).await?;
//!
//!     let file = b2::StartLargeFile::builder()
//!         .bucket_id("some-bucket-id")
//!         .file_name(name)?
//!         .content_type("text/plain")
//!         .build()?;
//!
//!     let file = b2::start_large_file(&mut auth, file).await?;
//!
//!     let mut upload_auth = b2::get_upload_part_authorization(
//!         &mut auth,
//!         &file
//!     ).await?;
//!
//!     // Assuming a `calculate_sha1` function is defined:
//!     let sha1 = calculate_sha1(&data_part1);
//!     let sha2 = calculate_sha1(&data_part2);
//!
//!     let upload_req = b2::UploadFilePart::builder()
//!         .part_sha1_checksum(&sha1)
//!         .build();
//!
//!     let _part1 = b2::upload_file_part(
//!         &mut upload_auth,
//!         &upload_req,
//!         &data_part1,
//!     ).await?;
//!
//!     let upload_req = upload_req.create_next_part(Some(&sha2))?;
//!
//!     let _part2 = b2::upload_file_part(
//!         &mut upload_auth,
//!         &upload_req,
//!         &data_part2,
//!     ).await?;
//!
//!     Ok(b2::finish_large_file_upload(
//!         &mut auth,
//!         &file,
//!         &[sha1, sha2],
//!     ).await?)
//! }
//! ```

use std::fmt;

use crate::{
    prelude::*,
    account::Capability,
    bucket::{
        Bucket,
        FileRetentionMode,
        FileRetentionPolicy,
        ServerSideEncryption,
    },
    client::{HeaderMap, HttpClient},
    error::*,
    types::ContentDisposition,
    validate::{
        validate_content_disposition,
        validate_file_metadata_size,
        validated_file_info,
        validated_file_name,
    },
};

pub use http_types::{
    cache::{CacheControl, Expires},
    content::ContentEncoding,
    mime::Mime,
};

use serde::{Serialize, Deserialize};


// Add a standard header to a serde_json::Map.
macro_rules! add_file_info {
    ($map:ident, $name:literal, $value:expr) => {
        if let Some(v) = $value {
            $map.insert($name.into(), serde_json::Value::from(v));
        }
    };
}

macro_rules! percent_encode {
    ($str:expr) => {
        percent_encoding::utf8_percent_encode(
            &$str,
            &crate::types::QUERY_ENCODE_SET
        ).to_string()
    };
}

#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
enum LegalHoldValue {
    On,
    Off,
}

impl fmt::Display for LegalHoldValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::On => write!(f, "on"),
            Self::Off => write!(f, "off"),
        }
    }
}

/// Determines whether there is a legal hold on a file.
#[derive(Debug, Deserialize)]
pub struct FileLegalHold {
    #[serde(rename = "isClientAuthorizedToRead")]
    can_read: bool,
    value: Option<LegalHoldValue>,
}

/// The action taken that resulted in a [File] object returned by the B2 API.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum FileAction {
    /// A large file upload has been started and is still in progress.
    Start,
    /// A file was uploaded.
    Upload,
    /// A file was copied from another file.
    Copy,
    /// The file (file version) has been marked as hidden.
    Hide,
    /// The file is a virtual folder.
    Folder,
}

// TODO: I may want to rename this to FileRetention since it's one of
// update_file_retention's parameters.
// This is different than but very similar to bucket::FileRetentionPolicy.
/// Sets the file retention mode and date/time during which the retention rule
/// applies.
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[allow(dead_code)]
pub struct FileRetentionSetting {
    mode: Option<FileRetentionMode>,
    #[serde(rename = "retainUntilTimestamp")]
    retain_until: Option<i64>,
}

impl FileRetentionSetting {
    pub fn new(
        mode: FileRetentionMode,
        retain_until: chrono::DateTime<chrono::Utc>
    ) -> Result<Self, BadData<chrono::DateTime<chrono::Utc>>> {
        if retain_until > chrono::Utc::now() {
            Ok(Self {
                mode: Some(mode),
                retain_until: Some(retain_until.timestamp_millis()),
            })
        } else {
            Err(BadData {
                value: retain_until,
                msg: "retain_until must be in the future".into(),
            })
        }
    }
}

// This is different than but very similar to bucket::FileLockConfiguration.
/// The retention settings for a file.
#[derive(Debug, Deserialize)]
pub struct FileRetention {
    #[serde(rename = "isClientAuthorizedToRead")]
    can_read: bool,
    value: FileRetentionSetting,
}

impl FileRetention {
    /// Get the file retention settings.
    ///
    /// If not authorized to read the settings, returns `None`.
    pub fn settings(&self) -> Option<FileRetentionSetting> {
        if self.can_read {
            Some(self.value)
        } else {
            None
        }
    }
}

// TODO: Rename to FileMetadata?
/// Metadata of a file stored in B2.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)]
pub struct File {
    account_id: Option<String>,
    action: FileAction,
    bucket_id: String,
    // Only relevant when action is "upload", will be 0 otherwise.
    content_length: u64,
    // Value is "none" for large files.
    content_sha1: Option<String>, // Max 64 elements
    content_md5: Option<String>, // Max 32 elements
    content_type: Option<String>,
    file_id: String,
    file_info: serde_json::Value,
    file_name: String,
    file_retention: Option<FileRetention>,
    legal_hold: Option<FileLegalHold>,
    server_side_encryption: Option<ServerSideEncryption>,
    // Milliseconds since midnight, 1970-1-1
    // If action is `Folder`, this will be 0.
    upload_timestamp: i64,
}

impl File {
    /// The action taken to result in this [File].
    pub fn action(&self) -> FileAction { self.action }

    /// The ID of the bucket containing the file.
    pub fn bucket_id(&self) -> &str { &self.bucket_id }

    /// The number of bytes stored in the file.
    ///
    /// Only meaningful when the [action](Self::action) is [FileAction::Upload]
    /// or [FileAction::Copy]; otherwise the value is `None`.
    pub fn content_length(&self) -> Option<u64> {
        match self.action {
            FileAction::Upload | FileAction::Copy => Some(self.content_length),
            _ => None,
        }
    }

    /// The SHA-1 checksum of the bytes in the file.
    ///
    /// There is no checksum for large files or when the [action](Self::action)
    /// is [FileAction::Hide] or [FileAction::Folder].
    pub fn sha1_checksum(&self) -> Option<&String> {
        match &self.content_sha1 {
            Some(v) => if v == "none" { None } else { Some(v) }
            None => None,
        }
    }

    /// The MD5 checksum of the bytes in the file.
    ///
    /// There is no checksum for large files or when the [action](Self::action)
    /// is [FileAction::Hide] or [FileAction::Folder].
    pub fn md5_checksum(&self) -> Option<&String> {
        self.content_md5.as_ref()
    }

    /// When [action](Self::action) is [FileAction::Upload],
    /// [FileAction::Start], or [FileAction::Copy], the file's MIME type.
    pub fn content_type(&self) -> Option<&String> {
        self.content_type.as_ref()
    }

    /// The B2 ID of the file.
    pub fn file_id(&self) -> &str { &self.file_id }

    /// User-specified and other file metadata.
    pub fn file_info(&self) -> &serde_json::Value {
        &self.file_info
    }

    /// The name of the file.
    pub fn file_name(&self) -> &str { &self.file_name }

    /// The file's retention policy.
    pub fn file_retention(&self) -> Option<&FileRetention> {
        self.file_retention.as_ref()
    }

    /// See if there is a legal hold on this file.
    ///
    /// Returns an error if the [Authorization] does not have
    /// [Capability::ReadFileLegalHolds].
    ///
    /// Returns `None` if a legal hold is not valid for the file type (e.g., the
    /// [action](Self::action) is `hide` or `folder`).
    pub fn has_legal_hold<E>(&self) -> Result<Option<bool>, Error<E>>
        where E: fmt::Debug + fmt::Display,
    {
        if let Some(hold) = &self.legal_hold {
            if ! hold.can_read {
                Err(Error::Unauthorized(Capability::ReadFileLegalHolds))
            } else if let Some(val) = &hold.value {
                match val {
                    LegalHoldValue::On => Ok(Some(true)),
                    LegalHoldValue::Off => Ok(Some(false)),
                }
            } else {
                Ok(None)
            }
        } else {
            Ok(None)
        }
    }

    /// The encryption settings for the file.
    pub fn encryption_settings(&self) -> Option<&ServerSideEncryption> {
        self.server_side_encryption.as_ref()
    }

    /// The date and time at which the file was uploaded.
    ///
    /// If the [action](Self::action) is `Folder`, returns `None`.
    pub fn upload_time(&self) -> Option<chrono::DateTime<chrono::Utc>> {
        use chrono::{TimeZone as _, Utc};

        match self.action {
            FileAction::Folder => None,
            _ => Some(Utc.timestamp_millis(self.upload_timestamp)),
        }
    }
}

/// A part of a large file currently being uploaded.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct FilePart {
    file_id: String,
    part_number: u16,
    content_length: u64,
    content_sha1: String,
    content_md5: Option<String>,
    server_side_encryption: Option<ServerSideEncryption>,
    upload_timestamp: i64,
}

impl FilePart {
    pub fn file_id(&self) -> &str { &self.file_id }
    pub fn part_number(&self) -> u16 { self.part_number }
    pub fn content_length(&self) -> u64 { self.content_length }
    pub fn sha1_checksum(&self) -> &str { &self.content_sha1 }
    pub fn md5_checksum(&self) -> Option<&String> { self.content_md5.as_ref() }

    pub fn encryption_settings(&self) -> Option<&ServerSideEncryption> {
        self.server_side_encryption.as_ref()
    }

    pub fn upload_timestamp(&self) -> chrono::DateTime<chrono::Utc> {
        use chrono::{TimeZone as _, Utc};

        Utc.timestamp_millis(self.upload_timestamp)
    }
}

/// A large file that was cancelled prior to upload completion.
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelledFileUpload {
    /// The ID of the cancelled file.
    pub file_id: String,
    /// The account that owns the file.
    pub account_id: String,
    /// The bucket the file was being uploaded to.
    pub bucket_id: String,
    /// The file's name.
    pub file_name: String,
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct DeletedFile {
    pub file_id: String,
    pub file_name: String,
}

/// Cancel the uploading of a large file and delete any parts already uploaded.
pub async fn cancel_large_file<C, E>(auth: &mut Authorization<C>, file: File)
-> Result<CancelledFileUpload, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    cancel_large_file_by_id(auth, file.file_id).await
}

/// Cancel the uploading of a large file and delete any parts already uploaded.
///
/// See [cancel_large_file] for documentation on use.
pub async fn cancel_large_file_by_id<C, E>(
    auth: &mut Authorization<C>,
    id: impl AsRef<str>
) -> Result<CancelledFileUpload, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    require_capability!(auth, Capability::WriteFiles);

    let res = auth.client.post(auth.api_url("b2_cancel_large_file"))
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token).unwrap()
        .with_body_json(serde_json::json!({ "fileId": id.as_ref() }))
        .send().await?;

    let info: B2Result<CancelledFileUpload> = serde_json::from_slice(&res)?;
    info.into()
}

/// A byte-range to retrieve a portion of a file.
///
/// Both `start` and `end` are inclusive.
#[derive(Debug, Clone, Serialize)]
#[serde(into = "String")]
pub struct ByteRange { start: u64, end: u64 }

impl From<ByteRange> for String {
    fn from(r: ByteRange) -> String {
        format!("bytes={}-{}", r.start, r.end)
    }
}

impl fmt::Display for ByteRange {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "bytes={}-{}", self.start, self.end)
    }
}

impl ByteRange {
    // TODO: It would be reasonable to misremember/assume that the range is
    // exclusive of the end byte; should we use `new_inclusive` and
    // `new_exclusive` (bounded/unbounded?) functions instead? This forces
    // explicitly choosing one or the other. Name them `new_end_xxx` to be truly
    // clear?
    pub fn new(start: u64, end: u64) -> Result<Self, ValidationError> {
        if start <= end {
            Ok(Self { start, end })
        } else {
            Err(ValidationError::Incompatible(format!(
                "Invalid start and end for range: {} to {}", start, end
            )))
        }
    }

    pub fn start(&self) -> u64 { self.start }
    pub fn end(&self) -> u64 { self.end }
}

/// Describe the action to take with file metadata when copying a file.
#[derive(Debug, Eq, PartialEq, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum MetadataDirective {
    Copy,
    Replace,
}

/// A request to copy a file from a bucket, potentially to a different bucket.
///
/// Use [CopyFileBuilder] to create a `CopyFile`, then pass it to [copy_file].
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CopyFile<'a> {
    source_file_id: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    destination_bucket_id: Option<String>,
    file_name: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    range: Option<ByteRange>,
    metadata_directive: MetadataDirective,
    #[serde(skip_serializing_if = "Option::is_none")]
    content_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    file_info: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    file_retention: Option<FileRetentionPolicy>,
    #[serde(skip_serializing_if = "Option::is_none")]
    legal_hold: Option<LegalHoldValue>,
    #[serde(rename = "sourceServerSideEncryption")]
    #[serde(skip_serializing_if = "Option::is_none")]
    source_encryption: Option<ServerSideEncryption>,
    #[serde(rename = "destinationServerSideEncryption")]
    #[serde(skip_serializing_if = "Option::is_none")]
    dest_encryption: Option<ServerSideEncryption>,
}

impl<'a> CopyFile<'a> {
    pub fn builder() -> CopyFileBuilder<'a> {
        CopyFileBuilder::default()
    }
}

/// A builder to create a [CopyFile] request.
///
/// See <https://www.backblaze.com/b2/docs/b2_copy_file.html> for further
/// information.
#[derive(Default)]
pub struct CopyFileBuilder<'a> {
    source_file_id: Option<String>,
    destination_bucket_id: Option<String>,
    file_name: Option<&'a str>,
    range: Option<ByteRange>,
    metadata_directive: Option<MetadataDirective>,
    content_type: Option<String>,
    file_info: Option<serde_json::Value>,
    file_retention: Option<FileRetentionPolicy>,
    legal_hold: Option<LegalHoldValue>,
    source_encryption: Option<ServerSideEncryption>,
    dest_encryption: Option<ServerSideEncryption>,

    // To merge into file_info on build if metadata_directive is Replace:
    last_modified: Option<i64>,
    sha1_checksum: Option<&'a str>,
    content_disposition: Option<String>,
    content_language: Option<String>,
    expires: Option<String>,
    cache_control: Option<String>,
    content_encoding: Option<String>,
}

impl<'a> CopyFileBuilder<'a> {
    /// Obtain the source file ID and encryption settings for the copy
    /// operation.
    pub fn source_file(mut self, file: &File) -> Self {
        self.source_encryption = file.server_side_encryption.clone();
        self.source_file_id(&file.file_id)
    }

    /// Set the source file ID of the file to copy.
    pub fn source_file_id(mut self, file: impl Into<String>) -> Self {
        self.source_file_id = Some(file.into());
        self
    }

    /// Set the destination bucket for the new file.
    ///
    /// If not provided, the same bucket ID as the source file is used.
    ///
    /// Both buckets must belong to the same account.
    pub fn destination_bucket_id(mut self, bucket: impl Into<String>) -> Self {
        self.destination_bucket_id = Some(bucket.into());
        self
    }

    /// Set the filename to use for the new file.
    pub fn destination_file_name(mut self, name: &'a str)
    -> Result<Self, FileNameValidationError> {
        self.file_name = Some(validated_file_name(name)?);
        Ok(self)
    }

    /// If provided, only copy the specified byte range of the source file.
    pub fn range(mut self, range: ByteRange) -> Self {
        self.range = Some(range);
        self
    }

    /// Determine whether to copy the source metadata to the new file.
    ///
    /// If [MetadataDirective::Copy] (the default), the source metadata will be
    /// copied to the new file.
    ///
    /// If [MetadataDirective::Replace], the new file's metadata will be empty
    /// or determined by the information provided via
    /// [content_type](Self::content_type) and [file_info](Self::file_info).
    pub fn metadata_directive(mut self, directive: MetadataDirective) -> Self {
        self.metadata_directive = Some(directive);
        self
    }

    /// Set the content-type of the file.
    ///
    /// The content-type can only be set if
    /// [metadata_directive](Self::metadata_directive) is
    /// [MetadataDirective::Replace].
    pub fn content_type(mut self, content_type: impl Into<String>) -> Self {
        self.content_type = Some(content_type.into());
        self
    }

    /// Set user-specified file metadata.
    ///
    /// The file information can only be set if
    /// [metadata_directive](Self::metadata_directive) is
    /// [MetadataDirective::Replace].
    ///
    /// For the following headers, use their corresponding methods instead of
    /// setting the values here:
    ///
    /// * X-Bz-Info-src_last_modified_millis:
    ///   [last_modified](Self::last_modified)
    /// * X-Bz-Info-large_file_sha1: [sha1_checksum](Self::sha1_checksum)
    /// * Content-Disposition: [content_disposition](Self::content_disposition)
    /// * Content-Language: [content_language](Self::content_language)
    /// * Expires: [expiration](Self::expiration)
    /// * Cache-Control: [cache_control](Self::cache_control)
    /// * Content-Encoding: [content_encoding](Self::content_encoding)
    ///
    /// If any of the above are set here and via their methods, the value from
    /// the method will override the value specified here.
    pub fn file_info(mut self, info: serde_json::Value)
    -> Result<Self, ValidationError> {
        self.file_info = Some(validated_file_info(info)?);
        Ok(self)
    }

    /// Set the file-retention settings for the new file.
    ///
    /// Setting this requires [Capability::WriteFileRetentions].
    pub fn file_retention(mut self, retention: FileRetentionPolicy) -> Self {
        self.file_retention = Some(retention);
        self
    }

    /// Enable legal hold status for the new file.
    pub fn with_legal_hold(mut self) -> Self {
        self.legal_hold = Some(LegalHoldValue::On);
        self
    }

    /// Do not enable legal hold status for the new file.
    pub fn without_legal_hold(mut self) -> Self {
        self.legal_hold = Some(LegalHoldValue::Off);
        self
    }

    /// Specify the server-side encryption settings on the source file.
    ///
    /// Calling [source_file](Self::source_file) will set this from the file
    /// object.
    pub fn source_encryption_settings(mut self, settings: ServerSideEncryption)
    -> Self {
        self.source_encryption = Some(settings);
        self
    }

    /// Specify the server-side encryption settings for the destination file.
    ///
    /// If not provided, the bucket's default settings will be used.
    pub fn destination_encryption_settings(
        mut self,
        settings: ServerSideEncryption
    ) -> Self {
        self.dest_encryption = Some(settings);
        self
    }

    /// The time of the file's last modification.
    pub fn last_modified(mut self, time: chrono::DateTime<chrono::Utc>) -> Self
    {
        self.last_modified = Some(time.timestamp_millis());
        self
    }

    /// The SHA1 checksum of the file's contents.
    ///
    /// B2 will use this to verify the accuracy of the file upload, and it will
    /// be returned in the header `X-Bz-Content-Sha1` when downloading the file.
    pub fn sha1_checksum(mut self, checksum: &'a str) -> Self {
        self.sha1_checksum = Some(checksum);
        self
    }

    /// The value to use for the `Content-Disposition` header when downloading
    /// the file.
    ///
    /// Note that the download request can override this value.
    pub fn content_disposition(mut self, disposition: ContentDisposition)
    -> Result<Self, ValidationError> {
        validate_content_disposition(&disposition.0, false)?;

        self.content_disposition = Some(percent_encode!(disposition.0));
        Ok(self)
    }

    /// The value to use for the `Content-Language` header when downloading the
    /// file.
    ///
    /// Note that the download request can override this value.
    pub fn content_language(mut self, language: impl Into<String>) -> Self {
        // TODO: validate content_language
        self.content_language = Some(percent_encode!(language.into()));
        self
    }

    /// The value to use for the `Expires` header when the file is downloaded.
    ///
    /// Note that the download request can override this value.
    pub fn expiration(mut self, expiration: Expires) -> Self {
        let expires = percent_encode!(expiration.value().to_string());

        self.expires = Some(expires);
        self
    }

    /// The value to use for the `Cache-Control` header when the file is
    /// downloaded.
    ///
    /// This would override the value set at the bucket level, and can be
    /// overriden by a download request.
    pub fn cache_control(mut self, cache_control: CacheControl) -> Self {
        self.cache_control = Some(cache_control.value().to_string());
        self
    }

    /// The value to use for the `Content-Encoding` header when the file is
    /// downloaded.
    ///
    /// Note that this can be overriden by a download request.
    pub fn content_encoding(mut self, encoding: ContentEncoding) -> Self {
        let encoding = percent_encode!(format!("{}", encoding.encoding()));
        self.content_encoding = Some(encoding);
        self
    }

    /// Create a [CopyFile] object.
    ///
    /// # Returns
    ///
    /// Returns [ValidationError::MissingData] if the source file or destination
    /// filename are not set.
    ///
    /// Returns [ValidationError::Incompatible] if the
    /// [metadata_directive](Self::metadata_directive) is
    /// [MetadataDirective::Copy] or was not provided AND
    /// [content_type](Self::content_type) or [file_info](Self::file_info) were
    /// set.
    pub fn build(self) -> Result<CopyFile<'a>, ValidationError> {
        let source_file_id = self.source_file_id.ok_or_else(||
            ValidationError::MissingData(
                "The source file ID is required".into()
            )
        )?;

        let file_name = self.file_name.ok_or_else(||
            ValidationError::MissingData(
                "The new file name must be specified".into()
            )
        )?;

        let metadata_directive = self.metadata_directive
            .unwrap_or(MetadataDirective::Copy);

        if matches!(metadata_directive, MetadataDirective::Copy) {
            if self.content_type.is_some() {
                return Err(ValidationError::Incompatible(
                    "When copying a file, a new content-type cannot be set"
                        .into()
                ));
            } else if self.file_info.is_some() {
                return Err(ValidationError::Incompatible(
                    "When copying a file, setting new file info is invalid"
                        .into()
                ));
            }
        }

        let file_info = if let Some(mut file_info) = self.file_info {
            let info_map = file_info.as_object_mut()
                .expect("file_info is not a JSON object");

            add_file_info!(info_map, "src_last_modified_millis",
                self.last_modified.map(|v| v.to_string()));
            add_file_info!(info_map, "large_file_sha1", self.sha1_checksum);
            add_file_info!(info_map, "b2-content-disposition",
                self.content_disposition);
            add_file_info!(info_map, "b2-content-language",
                self.content_language);
            add_file_info!(info_map, "b2-expires", self.expires);
            add_file_info!(info_map, "b2-content-encoding",
                self.content_encoding);

            Some(file_info)
        } else {
            None
        };

        validate_file_metadata_size(
            file_name,
            file_info.as_ref(),
            self.dest_encryption.as_ref()
        )?;

        Ok(CopyFile {
            source_file_id,
            destination_bucket_id: self.destination_bucket_id,
            file_name,
            range: self.range,
            metadata_directive,
            content_type: self.content_type,
            file_info,
            file_retention: self.file_retention,
            legal_hold: self.legal_hold,
            source_encryption: self.source_encryption,
            dest_encryption: self.dest_encryption,
        })
    }
}

/// Copy an existing file to a new file, possibly on a different bucket.
///
/// The new file must be less than 5 GB. Use [copy_file_part] to copy larger
/// files.
///
/// If copying from one bucket to another, both buckets must belong to the same
/// account.
pub async fn copy_file<'a, C, E>(
    auth: &mut Authorization<C>,
    file: CopyFile<'_>
) -> Result<File, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    require_capability!(auth, Capability::WriteFiles);
    if file.file_retention.is_some() {
        require_capability!(auth, Capability::WriteFileRetentions);
    }
    if file.legal_hold.is_some() {
        require_capability!(auth, Capability::WriteFileLegalHolds);
    }
    if file.dest_encryption.is_some() {
        require_capability!(auth, Capability::WriteBucketEncryption);
    }

    let res = auth.client.post(auth.api_url("b2_copy_file"))
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token).unwrap()
        .with_body_json(serde_json::to_value(file)?)
        .send().await?;

    let file: B2Result<File> = serde_json::from_slice(&res)?;
    file.into()
}

/// A request to copy from an existing file to a part of a large file.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CopyFilePart<'a> {
    source_file_id: &'a str,
    large_file_id: &'a str,
    part_number: u16,
    #[serde(skip_serializing_if = "Option::is_none")]
    range: Option<ByteRange>,
    #[serde(skip_serializing_if = "Option::is_none")]
    source_server_side_encryption: Option<&'a ServerSideEncryption>,
    #[serde(skip_serializing_if = "Option::is_none")]
    destination_server_side_encryption: Option<&'a ServerSideEncryption>,
}

impl<'a> CopyFilePart<'a> {
    pub fn builder() -> CopyFilePartBuilder<'a> {
        CopyFilePartBuilder::default()
    }
}

/// A builder to create a [CopyFilePart] request.
#[derive(Default)]
pub struct CopyFilePartBuilder<'a> {
    source_file: Option<&'a str>,
    large_file: Option<&'a str>,
    part_number: Option<u16>,
    range: Option<ByteRange>,
    source_encryption: Option<&'a ServerSideEncryption>,
    dest_encryption: Option<&'a ServerSideEncryption>,
}

impl<'a> CopyFilePartBuilder<'a> {
    /// Set the source file to copy from and its encryption settings.
    pub fn source_file(mut self, file: &'a File) -> Self {
        self.source_file = Some(&file.file_id);
        self.source_encryption = file.server_side_encryption.as_ref();
        self
    }

    /// Set the source file to copy from.
    pub fn source_file_id(mut self, file: &'a str) -> Self {
        self.source_file = Some(file);
        self
    }

    /// Set the large file to copy data to and its encryption settings.
    pub fn destination_large_file(mut self, file: &'a File) -> Self {
        self.large_file = Some(&file.file_id);

        if let Some(enc) = self.dest_encryption {
            if ! matches!(enc, ServerSideEncryption::NoEncryption) {
                self.dest_encryption = Some(enc);
            }
        }

        self
    }

    /// Set  the large file to copy data to.
    pub fn destination_large_file_id(mut self, file: &'a str) -> Self {
        self.large_file = Some(file);
        self
    }

    /// Set the number of this part.
    ///
    /// Part numbers increment from 1 to 10,000 inclusive.
    pub fn part_number(mut self, part_num: u16) -> Result<Self, ValidationError>
    {
        #[allow(clippy::manual_range_contains)]
        if part_num < 1 || part_num > 10000 {
            return Err(ValidationError::OutOfBounds(format!(
                "part_num must be between 1 and 10,000 inclusive. Was {}",
                part_num
            )));
        }

        self.part_number = Some(part_num);
        Ok(self)
    }

    /// Set the range of bytes from the source file to copy.
    ///
    /// If no range is specified, the entire file is copied.
    pub fn range(mut self, range: ByteRange) -> Self {
        self.range = Some(range);
        self
    }

    /// Set the encryption settings of the source file.
    ///
    /// This must match the settings with which the file was encrypted.
    pub fn source_encryption_settings(mut self, enc: &'a ServerSideEncryption)
    -> Self {
        self.source_encryption = Some(enc);
        self
    }

    /// Set the encryption settings of the destination file.
    ///
    /// This must match the settings passed to [start_large_file].
    pub fn destination_encryption_settings(
        mut self,
        enc: &'a ServerSideEncryption
    ) -> Self {
        self.dest_encryption = Some(enc);
        self
    }

    /// Create a [CopyFilePart] request object.
    pub fn build(self) -> Result<CopyFilePart<'a>, ValidationError> {
        let source_file_id = self.source_file.ok_or_else(||
            ValidationError::MissingData("source_file is required".into())
        )?;

        let large_file_id = self.large_file.ok_or_else(||
            ValidationError::MissingData(
                "destination_large_file is required".into()
            )
        )?;

        let part_number = self.part_number.ok_or_else(||
            ValidationError::MissingData("part_number is required".into())
        )?;

        Ok(CopyFilePart {
            source_file_id,
            large_file_id,
            part_number,
            range: self.range,
            source_server_side_encryption: self.source_encryption,
            destination_server_side_encryption: self.dest_encryption,
        })
    }
}

/// Copy from an existing file to a new large file.
///
/// The [Authorization] must have [Capability::WriteFiles], and if the bucket is
/// private, [Capability::ReadFiles].
pub async fn copy_file_part<C, E>(
    auth: &mut Authorization<C>,
    file_part: CopyFilePart<'_>
) -> Result<FilePart, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    require_capability!(auth, Capability::WriteFiles);

    let res = auth.client.post(auth.api_url("b2_copy_part"))
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token).unwrap()
        .with_body_json(serde_json::to_value(file_part)?)
        .send().await?;

    let part: B2Result<FilePart> = serde_json::from_slice(&res)?;
    part.into()
}

/// Declare whether to bypass file lock restrictions when performing an action
/// on a [File].
///
/// Bypassing governance rules requires [Capability::BypassGovernance].
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum BypassGovernance { Yes, No }

/// Delete a version of a file.
///
/// If the version is the file's latest version and there are older versions,
/// the most-recent older version will become the current version of the file.
///
/// If called on an unfinished large file, has the same effect as
/// [cancel_large_file].
pub async fn delete_file_version<C, E>(
    auth: &mut Authorization<C>,
    file: File,
    bypass_governance: BypassGovernance,
) -> Result<DeletedFile, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    delete_file_version_by_name_id(
        auth,
        &file.file_name,
        &file.file_id,
        bypass_governance
    ).await
}

/// Retrieve the headers that will be returned when the specified file is
/// downloaded.
///
/// See <https://www.backblaze.com/b2/docs/b2_download_file_by_id.html> for a
/// list of headers that may be returned.
pub async fn download_file_headers<C, E>(
    auth: &mut Authorization<C>,
    file: &File
) -> Result<HeaderMap, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    download_file_headers_by_id(auth, &file.file_id).await
}

/// Retrieve the headers that will be returned when the specified file is
/// downloaded.
///
/// See <https://www.backblaze.com/b2/docs/b2_download_file_by_id.html> for a
/// list of headers that may be returned.
pub async fn download_file_headers_by_id<C, E>(
    auth: &mut Authorization<C>,
    file_id: impl AsRef<str>
) -> Result<HeaderMap, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    // TODO: This is probably only required for private buckets; public buckets
    // don't require an authorization token, but the docs read as if this is
    // necessary if provided. Need to test, and if necessary allow downloading
    // the file without passing the authorization token.
    require_capability!(auth, Capability::ReadFiles);

    let res = auth.client.head(
            format!("{}?fileId={}",
                auth.download_url("b2_download_file_by_id"),
                file_id.as_ref()
            )
        )
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token).unwrap()
        .send_keep_headers().await?;

    Ok(res.1)
}

#[derive(Debug)]
enum FileHandle<'a> {
    Id(&'a str),
    Name((String, &'a str)), // (Percent-encoded file name, bucket name)
}

/// A request to download a file or a portion of a file from the B2 API.
///
/// A simple file request can be created via [with_name](Self::with_name) or
/// [with_id](Self::with_id); for more complex requests use a
/// [DownloadFileBuilder].
///
/// If you use self-managed server-side encryption, you must use
/// [DownloadFileBuilder] to pass the encryption information.
///
/// See <https://www.backblaze.com/b2/docs/b2_download_file_by_id.html> for
/// information on downloading files, including the list of headers that may be
/// returned.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DownloadFile<'a> {
    #[serde(skip_serializing)]
    file: FileHandle<'a>,
    #[serde(skip_serializing)]
    range: Option<ByteRange>,
    #[serde(skip_serializing_if = "Option::is_none")]
    b2_content_disposition: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    b2_content_language: Option<&'a str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    b2_expires: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    b2_cache_control: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    b2_content_encoding: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    b2_content_type: Option<String>,
    #[serde(skip_serializing)]
    encryption: Option<ServerSideEncryption>,
}

impl<'a> DownloadFile<'a> {
    /// Download a file with the specified file ID.
    pub fn with_id(id: &'a str) -> Self {
        Self {
            file: FileHandle::Id(id),
            range: None,
            b2_content_disposition: None,
            b2_content_language: None,
            b2_expires: None,
            b2_cache_control: None,
            b2_content_encoding: None,
            b2_content_type: None,
            encryption: None,
        }
    }

    /// Download a file with the specified file name.
    ///
    /// The name will be percent-encoded.
    pub fn with_name(name: &str, bucket: &'a str) -> Self {
        Self {
            file: FileHandle::Name((percent_encode!(name), bucket)),
            range: None,
            b2_content_disposition: None,
            b2_content_language: None,
            b2_expires: None,
            b2_cache_control: None,
            b2_content_encoding: None,
            b2_content_type: None,
            encryption: None,
        }
    }

    pub fn builder() -> DownloadFileBuilder<'a> {
        DownloadFileBuilder::default()
    }

    /// Generate the public URL for a GET request for a file in a public bucket.
    ///
    /// A file in a public bucket does not require an authorization token to
    /// access, making this link suitable for distribution (e.g., embedding in a
    /// web page).
    ///
    /// You must provide an [Authorization] or [DownloadAuthorization] that has
    /// access to the file.
    pub fn public_url<'b, C, D, E>(&self, auth: D) -> String
        where C: HttpClient<Error=Error<E>> + 'b,
              D: Into<&'b DownloadAuth<'b, C>>,
              E: fmt::Debug + fmt::Display,
    {
        let auth = auth.into();

        match &self.file {
            FileHandle::Id(id) => format!(
                "{}?fileId={}",
                auth.download_url("b2_download_file_by_id"),
                id
            ),
            FileHandle::Name((name, bucket)) => format!(
                "{}/file/{}/{}?",
                auth.download_get_url(),
                bucket,
                name
            ),
        }
    }
}

#[derive(Default)]
pub struct DownloadFileBuilder<'a> {
    file: Option<FileHandle<'a>>,
    range: Option<ByteRange>,
    content_disposition: Option<&'a str>,
    content_language: Option<&'a str>,
    expires: Option<String>,
    cache_control: Option<String>,
    content_encoding: Option<String>,
    content_type: Option<String>,
    encryption: Option<ServerSideEncryption>,
}

impl<'a> DownloadFileBuilder<'a> {
    /// Download a file with the specified file name.
    ///
    /// The name will be percent-encoded.
    ///
    /// If both [file_name](Self::file_name) and [file_id](Self::file_id) are
    /// provided, the last one will be used.
    pub fn file_name(mut self, name: &str, bucket: &'a str) -> Self {
        self.file = Some(FileHandle::Name((percent_encode!(name), bucket)));
        self
    }

    /// Download a file with the specified file ID.
    ///
    /// If both [file_name](Self::file_name) and [file_id](Self::file_id) are
    /// provided, the last one will be used.
    pub fn file_id(mut self, id: &'a str) -> Self {
        self.file = Some(FileHandle::Id(id));
        self
    }

    /// Specify the byte range of the file to download.
    ///
    /// There will be a Content-Range header that specifies the bytes returned
    /// and the total number of bytes.
    ///
    /// The HTTP status code when a partial file is returned is `206 Partial
    /// Content` rather than `200 OK`.
    pub fn range(mut self, range: ByteRange) -> Self {
        self.range = Some(range);
        self
    }

    /// Override the Content-Disposition header of the response with the one
    /// provided.
    ///
    /// If including this header will exceed the 7,000 byte header limit (2,048
    /// bytes if using server-side encryption), the request will be rejected.
    pub fn content_disposition(mut self, disposition: &'a ContentDisposition)
    -> Result<Self, ValidationError> {
        validate_content_disposition(&disposition.0, false)?;
        self.content_disposition = Some(&disposition.0);
        Ok(self)
    }

    /// Override the Content-Language header of the response with the one
    /// provided.
    ///
    /// If including this header will exceed the 7,000 byte header limit (2,048
    /// bytes if using server-side encryption), the request will be rejected.
    pub fn content_language(mut self, language: &'a str) -> Self {
        // TODO: validate content_language
        self.content_language = Some(language);
        self
    }

    /// Override the Expires header of the response with the one provided.
    ///
    /// If including this header will exceed the 7,000 byte header limit (2,048
    /// bytes if using server-side encryption), the request will be rejected.
    pub fn expiration(mut self, expiration: Expires) -> Self {
        self.expires = Some(expiration.value().to_string());
        self
    }

    /// Override the Cache-Control header of the response with the one provided.
    ///
    /// If including this header will exceed the 7,000 byte header limit (2,048
    /// bytes if using server-side encryption), the request will be rejected.
    pub fn cache_control(mut self, cache_control: CacheControl) -> Self {
        self.cache_control = Some(cache_control.value().to_string());
        self
    }

    /// Override the Content-Encoding header of the response with the one
    /// provided.
    ///
    /// If including this header will exceed the 7,000 byte header limit (2,048
    /// bytes if using server-side encryption), the request will be rejected.
    pub fn content_encoding(mut self, encoding: ContentEncoding) -> Self {
        self.content_encoding = Some(format!("{}", encoding.encoding()));
        self
    }

    /// Override the Content-Type header of the response with the one provided.
    ///
    /// If including this header will exceed the 7,000 byte header limit (2,048
    /// bytes if using server-side encryption), the request will be rejected.
    pub fn content_type(mut self, content_type: impl Into<Mime>) -> Self {
        self.content_type = Some(content_type.into().to_string());
        self
    }

    /// Set the encryption settings to use for the file.
    ///
    /// This is required if using self-managed server-side encryption.
    pub fn encryption_settings(mut self, settings: ServerSideEncryption)
    -> Self {
        self.encryption = Some(settings);
        self
    }

    /// Build a [DownloadFile] request.
    pub fn build(self) -> Result<DownloadFile<'a>, ValidationError> {
        let file = self.file.ok_or_else(|| ValidationError::MissingData(
            "Must specify the file to download".into()
        ))?;

        Ok(DownloadFile {
            file,
            range: self.range,
            b2_content_disposition: self.content_disposition,
            b2_content_language: self.content_language,
            b2_expires: self.expires,
            b2_cache_control: self.cache_control,
            b2_content_encoding: self.content_encoding,
            b2_content_type: self.content_type,
            encryption: self.encryption,
        })
    }
}

/// Allow downloading files via an `Authorization` or `DownloadAuthorization`.
///
/// You do not need to use this type explicitly.
pub enum DownloadAuth<'a, C>
    where C: HttpClient
{
    Auth(&'a mut Authorization<C>),
    Download(&'a mut DownloadAuthorization<C>),
}

impl<'a, C> DownloadAuth<'a, C>
    where C: HttpClient,
{
    fn download_get_url(&self) -> &str {
        match self {
            Self::Auth(auth) => auth.download_get_url(),
            Self::Download(auth) => &auth.download_url,
        }
    }

    fn download_url(&self, endpoint: impl AsRef<str>) -> String {
        match self {
            Self::Auth(auth) => auth.download_url(endpoint),
            Self::Download(auth) =>
                format!("{}/b2api/v2/{}", auth.download_url, endpoint.as_ref())
        }
    }

    fn authorization_token(&self) -> &str {
        match self {
            Self::Auth(auth) => &auth.authorization_token,
            Self::Download(auth) => &auth.authorization_token,
        }
    }

    fn has_capability(&self, cap: Capability) -> bool {
        match self {
            Self::Auth(auth) => auth.has_capability(cap),
            _ => true,
        }
    }
}

impl<'a, C> From<&'a mut Authorization<C>> for DownloadAuth<'a, C>
    where C: HttpClient,
{
    fn from(auth: &'a mut Authorization<C>) -> Self {
        Self::Auth(auth)
    }
}

impl<'a, C> From<&'a mut DownloadAuthorization<C>> for DownloadAuth<'a, C>
    where C: HttpClient,
{
    fn from(auth: &'a mut DownloadAuthorization<C>) -> Self {
        Self::Download(auth)
    }
}

/// Download a file from the B2 service.
///
/// If downloading a file by name, you may provide a mutable reference to either
/// an [Authorization] or a [DownloadAuthorization].
///
/// Downloading files by ID requires an `Authorization`. If provided with a
/// `DownloadAuthorization`, returns `Error::MissingAuthorization`.
pub async fn download_file<'a, C, E>(
    auth: impl Into<DownloadAuth<'a, C>>,
    file: DownloadFile<'_>
) -> Result<(Vec<u8>, HeaderMap), Error<E>>
    where C: HttpClient<Error=Error<E>> + 'a,
          E: fmt::Debug + fmt::Display,
{
    match file.file {
        FileHandle::Id(_) => {
            match auth.into() {
                DownloadAuth::Auth(auth) => download_file_by_id(auth, file)
                    .await,
                _ => Err(Error::MissingAuthorization),
            }
        },
        FileHandle::Name(_) => download_file_by_name(auth, file).await
    }
}

async fn download_file_by_id<C, E>(
    auth: &mut Authorization<C>,
    file: DownloadFile<'_>
) -> Result<(Vec<u8>, HeaderMap), Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    // TODO: This is probably only required for private buckets; public buckets
    // don't require an authorization token, but the docs read as if this is
    // necessary if provided. Need to test, and if necessary allow downloading
    // the file without passing the authorization token.
    require_capability!(auth, Capability::ReadFiles);

    let file_id = match file.file {
        FileHandle::Id(id) => id,
        FileHandle::Name(_) => panic!("Call download_file_by_name() instead"),
    };

    let mut file_req = serde_json::to_value(&file)?;
    file_req["fileId"] = serde_json::Value::String(file_id.into());

    let mut req = auth.client.post(auth.download_url("b2_download_file_by_id"))
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token).unwrap()
        .with_body_json(file_req);

    if let Some(range) = file.range {
        req = req.with_header("Range", &range.to_string())?;
    }

    if let Some(ServerSideEncryption::SelfManaged(enc)) = file.encryption {
        req = req
            .with_header(
                "X-Bz-Server-Side-Encryption-Customer-Algorithm",
                &enc.algorithm.to_string()
            )?
            .with_header(
                "X-Bz-Server-Side-Encryption-Customer-Key",
                &enc.key
            )?
            .with_header(
                "X-Bz-Server-Side-Encryption-Customer-Key-Md5",
                &enc.digest
            )?;
    }

    let (body, headers) = req.send_keep_headers().await?;

    // An error from Backblaze would successfully deserialize as Vec<u8>, so we
    // need to check for it specifically.
    let res: Result<B2Error, _> = serde_json::from_slice(&body);
    match res {
        Ok(e) => Err(e.into()),
        Err(_) => Ok((body, headers)),
    }
}

async fn download_file_by_name<'a, C, E>(
    auth: impl Into<DownloadAuth<'a, C>>,
    file: DownloadFile<'_>
) -> Result<(Vec<u8>, HeaderMap), Error<E>>
    where C: HttpClient<Error=Error<E>> + 'a,
          E: fmt::Debug + fmt::Display,
{
    let mut auth = auth.into();

    // TODO: This is probably only required for private buckets; public buckets
    // don't require an authorization token, but the docs read as if this is
    // necessary if provided. Need to test, and if necessary allow downloading
    // the file without passing the authorization token.
    require_capability!(auth, Capability::ReadFiles);
    assert!(matches!(file.file, FileHandle::Name(_)));

    let mut url = file.public_url(&auth).to_owned();

    macro_rules! add_param {
        ($str:ident, $name:literal, $obj:expr) => {
            $str.push_str($name);
            $str.push('=');
            $str.push_str($obj);
            $str.push('&'); // The trailing & will be ignored, so this is fine.
        };
    }

    macro_rules! add_opt_param {
        ($str:ident, $name:literal, $obj:expr) => {
            if let Some(s) = $obj {
                add_param!($str, $name, &s);
            }
        };
    }

    add_opt_param!(url, "b2ContentDisposition", file.b2_content_disposition);
    add_opt_param!(url, "b2ContentLanguage", file.b2_content_language);
    add_opt_param!(url, "b2Expires", file.b2_expires);
    add_opt_param!(url, "b2CacheControl", file.b2_cache_control);
    add_opt_param!(url, "b2ContentEncoding", file.b2_content_encoding);
    add_opt_param!(url, "b2ContentType", file.b2_content_type);

    if let Some(ServerSideEncryption::SelfManaged(enc)) = file.encryption {
        add_param!(url,
            "X-Bz-Server-Side-Encryption-Customer-Algorithm",
            &enc.algorithm.to_string()
        );
        add_param!(url,
            "X-Bz-Server-Side-Encryption-Customer-Key",
            &enc.key
        );
        add_param!(url,
            "X-Bz-Server-Side-Encryption-Customer-Key-Md5",
            &enc.digest
        );
    }

    let auth_token = auth.authorization_token().to_owned();

    let client = match auth {
        DownloadAuth::Auth(ref mut auth) => &mut auth.client,
        DownloadAuth::Download(ref mut auth) => &mut auth.client,
    };

    let mut req = client.get(url)
        .expect("Invalid URL")
        .with_header("Authorization", &auth_token).unwrap();

    if let Some(range) = file.range {
        req = req.with_header("Range", &range.to_string())?
    }

    let (body, headers) = req.send_keep_headers().await?;

    // An error from Backblaze would successfully deserialize as Vec<u8>, so we
    // need to check for it specifically.
    let res: Result<B2Error, _> = serde_json::from_slice(&body);
    match res {
        Ok(e) => Err(e.into()),
        Err(_) => Ok((body, headers)),
    }
}

/// Delete a version of a file.
///
/// If the version is the file's latest version and there are older versions,
/// the most-recent older version will become the current version of the file.
///
/// If called on an unfinished large file, has the same effect as
/// [cancel_large_file].
pub async fn delete_file_version_by_name_id<C, E>(
    auth: &mut Authorization<C>,
    file_name: impl AsRef<str>,
    file_id: impl AsRef<str>,
    bypass_governance: BypassGovernance,
) -> Result<DeletedFile, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    require_capability!(auth, Capability::DeleteFiles);

    let mut body = serde_json::json!({
        "fileName": &file_name.as_ref(),
        "fileId": &file_id.as_ref(),
    });

    if matches!(bypass_governance, BypassGovernance::Yes) {
        require_capability!(auth, Capability::BypassGovernance);
        body["bypassGovernance"] = serde_json::Value::Bool(true);
    }

    let res = auth.client.post(auth.api_url("b2_delete_file_version"))
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token).unwrap()
        .with_body_json(body)
        .send().await?;

    let file: B2Result<DeletedFile> = serde_json::from_slice(&res)?;
    file.into()
}

/// Complete the upload of a large file, merging all parts into a single [File].
///
/// This is the final step to uploading a large file. If the request times out,
/// it is recommended to call [get_file_info] to see if the file succeeded and
/// only repeat the call to `finish_large_file_upload` if the file is missing.
///
/// The `sha1_checksums` must be sorted ascending by part number.
///
/// The [Authorization] must have [Capability::WriteFiles].
pub async fn finish_large_file_upload<C, E>(
    auth: &mut Authorization<C>,
    file: &File,
    sha1_checksums: &[String],
) -> Result<File, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    finish_large_file_upload_by_id(auth, &file.file_id, sha1_checksums).await
}

/// Complete the upload of a large file, merging all parts into a single [File].
///
/// See [finish_large_file_upload] for documentation on use.
pub async fn finish_large_file_upload_by_id<C, E>(
    auth: &mut Authorization<C>,
    file_id: impl AsRef<str>,
    sha1_checksums: &[String],
) -> Result<File, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    use serde_json::json;

    require_capability!(auth, Capability::WriteFiles);

    let res = auth.client.post(auth.api_url("b2_finish_large_file"))
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token).unwrap()
        .with_body_json(json!( {
            "fileId": file_id.as_ref(),
            "partSha1Array": &sha1_checksums,
        }))
        .send().await?;

    let file: B2Result<File> = serde_json::from_slice(&res)?;
    file.into()
}

/// Retrieve metadata about a file stored in B2.
///
/// See <https://www.backblaze.com/b2/docs/b2_get_file_info.html> for further
/// information.
///
/// # Errors
///
/// This function will return an error if the file ID does not exist or it is
/// for a large file that has not been finished yet.
pub async fn get_file_info<C, E>(
    auth: &mut Authorization<C>,
    file_id: impl AsRef<str>
) -> Result<File, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    use serde_json::json;

    require_capability!(auth, Capability::ReadFiles);

    let res = auth.client.post(auth.api_url("b2_get_file_info"))
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token).unwrap()
        .with_body_json(json!({
            "fileId": file_id.as_ref(),
        }))
        .send().await?;

    let file_info: B2Result<File> = serde_json::from_slice(&res)?;
    match file_info {
        B2Result::Ok(mut info) => {
            if let Some(sha1) = &info.content_sha1 {
                if sha1 == "none" {
                    info.content_sha1 = None;
                }
            }

            Ok(info)
        },
        B2Result::Err(e) => Err(e.into()),
    }
}

/// A request to obtain a [DownloadAuthorization].
///
/// Use [DownloadAuthorizationRequestBuilder] to create a
/// `DownloadAuthorizationRequest`, then pass it to [get_download_authorization]
/// to obtain a [DownloadAuthorization].
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct DownloadAuthorizationRequest<'a> {
    bucket_id: &'a str,
    file_name_prefix: &'a str,
    valid_duration_in_seconds: Duration,
    #[serde(skip_serializing_if = "Option::is_none")]
    b2_content_disposition: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    b2_content_language: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    b2_expires: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    b2_cache_control: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    b2_content_encoding: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    b2_content_type: Option<String>,
}

impl<'a> DownloadAuthorizationRequest<'a> {
    pub fn builder() -> DownloadAuthorizationRequestBuilder<'a> {
        DownloadAuthorizationRequestBuilder::default()
    }
}

/// A builder to create a [DownloadAuthorizationRequest].
///
/// After building the `DownloadAuthorizationRequest`, pass it to
/// [get_download_authorization] to obtain a [DownloadAuthorization]
///
/// The bucket ID, file name prefix, and valid duration are required.
///
/// See <https://www.backblaze.com/b2/docs/b2_get_download_authorization.html>
/// for furter information.
#[derive(Default)]
pub struct DownloadAuthorizationRequestBuilder<'a> {
    // Required:
    bucket_id: Option<&'a str>,
    file_name_prefix: Option<&'a str>,
    valid_duration_in_seconds: Option<Duration>,
    // Optional:
    b2_content_disposition: Option<String>,
    b2_content_language: Option<String>,
    b2_expires: Option<String>,
    b2_cache_control: Option<String>,
    b2_content_encoding: Option<String>,
    b2_content_type: Option<String>,
}

impl<'a> DownloadAuthorizationRequestBuilder<'a> {
    /// Create a download authorization for the specified bucket ID.
    pub fn bucket_id(mut self, id: &'a str) -> Self {
        self.bucket_id = Some(id);
        self
    }

    /// Use the given file name prefix to determine what files the
    /// [DownloadAuthorization] will allow access to.
    pub fn file_name_prefix(mut self, name: &'a str)
    -> Result<Self, FileNameValidationError> {

        self.file_name_prefix = Some(validated_file_name(name)?);
        Ok(self)
    }

    /// Specify the amount of time for which the [DownloadAuthorization] will be
    /// valid.
    ///
    /// This must be between one second and one week, inclusive.
    pub fn duration(mut self, dur: chrono::Duration)
    -> Result<Self, ValidationError> {
        if dur < chrono::Duration::seconds(1)
            || dur > chrono::Duration::weeks(1)
        {
            return Err(ValidationError::OutOfBounds(
                "Duration must be between 1 and 604,800 seconds, inclusive"
                    .into()
            ));
        }

        self.valid_duration_in_seconds = Some(Duration(dur));
        Ok(self)
    }

    /// If specified, download requests must have this content disposition. The
    /// grammar is specified in RFC 6266, except that parameter names containing
    /// a '*' are not allowed.
    pub fn content_disposition(mut self, disposition: ContentDisposition)
    -> Self {
        self.b2_content_disposition = Some(disposition.0);
        self
    }

    /// If specified, download requests must have this content language. The
    /// grammar is specified in RFC 2616.
    pub fn content_language<S: Into<String>>(mut self, lang: S) -> Self {
        // TODO: Validate language.
        self.b2_content_language = Some(lang.into());
        self
    }

    /// If specified, download requests must have this expiration.
    pub fn expiration(mut self, expiration: Expires) -> Self {
        self.b2_expires = Some(expiration.value().to_string());
        self
    }

    /// If specified, download requests must have this cache control.
    pub fn cache_control(mut self, cache_control: CacheControl) -> Self {
        self.b2_cache_control = Some(cache_control.value().to_string());
        self
    }

    /// If specified, download requests must have this content encoding.
    pub fn content_encoding(mut self, encoding: ContentEncoding) -> Self {
        self.b2_content_encoding = Some(format!("{}", encoding.encoding()));
        self
    }

    /// If specified, download requests must have this content type.
    pub fn content_type(mut self, content_type: impl Into<Mime>) -> Self {
        self.b2_content_type = Some(content_type.into().to_string());
        self
    }

    /// Build a [DownloadAuthorizationRequest].
    pub fn build(self)
    -> Result<DownloadAuthorizationRequest<'a>, ValidationError> {
        let bucket_id = self.bucket_id
            .ok_or_else(|| ValidationError::MissingData(
                "A bucket ID must be provided".into()
            ))?;
        let file_name_prefix = self.file_name_prefix
            .ok_or_else(|| ValidationError::MissingData(
                "A filename prefix must be provided".into()
            ))?;
        let valid_duration_in_seconds = self.valid_duration_in_seconds
            .ok_or_else(|| ValidationError::MissingData(
                "The duration of the authorization token must be set".into()
            ))?;

        Ok(DownloadAuthorizationRequest {
            bucket_id,
            file_name_prefix,
            valid_duration_in_seconds,
            b2_content_disposition: self.b2_content_disposition,
            b2_content_language: self.b2_content_language,
            b2_expires: self.b2_expires,
            b2_cache_control: self.b2_cache_control,
            b2_content_encoding: self.b2_content_encoding,
            b2_content_type: self.b2_content_type,
        })
    }
}

/// A capability token that authorizes downloading files from a private bucket.
#[derive(Debug)]
#[allow(dead_code)]
pub struct DownloadAuthorization<C>
    where C: HttpClient,
{
    client: C,
    api_url: String,
    download_url: String,

    bucket_id: String,
    file_name_prefix: String,
    authorization_token: String,
}

impl<C> DownloadAuthorization<C>
    where C: HttpClient + Clone,
{
    /// Get the ID of the bucket this `DownloadAuthorization` can access.
    pub fn bucket_id(&self) -> &str { &self.bucket_id }
    /// The file prefix that determines what files in the bucket are accessible
    /// via this `DownloadAuthorization`.
    pub fn file_name_prefix(&self) -> &str { &self.file_name_prefix }

    fn from_proto(
        proto: ProtoDownloadAuthorization,
        auth: &Authorization<C>,
    ) -> Self {
        Self {
            client: auth.client.clone(),
            api_url: auth.api_url.clone(),
            download_url: auth.download_url.clone(),
            bucket_id: proto.bucket_id,
            file_name_prefix: proto.file_name_prefix,
            authorization_token: proto.authorization_token,
        }
    }
}

#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ProtoDownloadAuthorization {
    bucket_id: String,
    file_name_prefix: String,
    authorization_token: String,
}

/// Generate a download authorization token to download files with a specific
/// prefix from a private B2 bucket.
///
/// The [Authorization] token must have [Capability::ShareFiles].
///
/// The returned [DownloadAuthorization] can be passed to
/// [download_file](crate::file::download_file) in place of an [Authorization]
/// when downloading files by name.
///
/// See <https://www.backblaze.com/b2/docs/b2_get_download_authorization.html>
/// for further information.
///
/// # Examples
///
/// ```no_run
/// # #[cfg(feature = "with_surf")]
/// # use b2_client::{
/// #     client::{HttpClient, SurfClient},
/// #     account::authorize_account,
/// #     file::{DownloadAuthorizationRequest, get_download_authorization},
/// # };
/// # #[cfg(feature = "with_surf")]
/// # async fn f() -> anyhow::Result<()> {
/// let mut auth = authorize_account(
///     SurfClient::default(),
///     "MY KEY ID",
///     "MY KEY"
/// ).await?;
///
/// let download_req = DownloadAuthorizationRequest::builder()
///     .bucket_id("MY BUCKET ID")
///     .file_name_prefix("my/files/")?
///     .duration(chrono::Duration::seconds(60))?
///     .build()?;
///
/// let download_auth = get_download_authorization(&mut auth, download_req)
///     .await?;
/// # Ok(()) }
/// ```
pub async fn get_download_authorization<'a, C, E>(
    auth: &mut Authorization<C>,
    download_req: DownloadAuthorizationRequest<'_>
) -> Result<DownloadAuthorization<C>, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    require_capability!(auth, Capability::ShareFiles);

    let res = auth.client.post(auth.api_url("b2_get_download_authorization"))
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token).unwrap()
        .with_body_json(serde_json::to_value(download_req)?)
        .send().await?;

    let proto_auth: B2Result<ProtoDownloadAuthorization> =
        serde_json::from_slice(&res)?;

    proto_auth.map(|a| DownloadAuthorization::from_proto(a, auth)).into()
}

/// An authorization to upload file contents to a B2 file.
#[derive(Deserialize)]
#[allow(dead_code)]
#[serde(rename_all = "camelCase")]
pub struct UploadPartAuthorization<'a, 'b, C, E>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    #[serde(skip_deserializing)]
    #[serde(default = "make_none")]
    auth: Option<&'a mut Authorization<C>>,
    #[serde(skip_deserializing)]
    #[serde(default = "make_none")]
    encryption: Option<&'b ServerSideEncryption>,
    file_id: String,
    upload_url: String,
    authorization_token: String,
}

fn make_none<T>() -> Option<T> { None }

/// Get an [UploadPartAuthorization] to upload data to a new B2 file.
///
/// Use the returned `UploadPartAuthorization` when calling [upload_file_part].
///
/// The `UploadPartAuthorization` is valid for 24 hours or until an endpoint
/// rejects an upload.
///
/// If uploading multiple parts concurrently, each thread or task needs its own
/// authorization.
///
/// The [Authorization] must have [Capability::WriteFiles].
///
/// # B2 API Difference
///
/// The equivalent B2 endpoint is called
/// [`b2_get_upload_url`](https://www.backblaze.com/b2/docs/b2_get_upload_part_url.html).
pub async fn get_upload_part_authorization<'a, 'b, C, E>(
    auth: &'a mut Authorization<C>,
    file: &'b File,
) -> Result<UploadPartAuthorization<'a, 'b, C, E>, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    get_upload_part_authorization_by_id(
        auth,
        &file.file_id,
        file.server_side_encryption.as_ref()
    ).await
}

/// Get an [UploadPartAuthorization] to upload data to a new B2 file.
///
/// See [get_upload_part_authorization] for documentation on retrieving the
/// authorization.
pub async fn get_upload_part_authorization_by_id<'a, 'b, C, E>(
    auth: &'a mut Authorization<C>,
    file_id: impl AsRef<str>,
    encryption: Option<&'b ServerSideEncryption>,
) -> Result<UploadPartAuthorization<'a, 'b, C, E>, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    use serde_json::json;

    require_capability!(auth, Capability::WriteFiles);

    let res = auth.client.post(auth.api_url("b2_get_upload_part_url"))
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token).unwrap()
        .with_body_json(json!({ "fileId": file_id.as_ref() }))
        .send().await?;

    let upload_auth: B2Result<UploadPartAuthorization<'_, '_, _, _>> =
        serde_json::from_slice(&res)?;

    upload_auth.map(move |mut a| {
        a.auth = Some(auth);
        a.encryption = encryption;
        a
    }).into()
}

/// An authorization to upload a file to a B2 bucket.
#[derive(Deserialize)]
#[allow(dead_code)]
#[serde(rename_all = "camelCase")]
pub struct UploadAuthorization<'a, C, E>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    #[serde(skip_deserializing)]
    #[serde(default = "make_none")]
    auth: Option<&'a mut Authorization<C>>,
    bucket_id: String,
    upload_url: String,
    authorization_token: String,
}

impl<'a, C, E> UploadAuthorization<'a, C, E>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    pub fn bucket_id(&self) -> &str { &self.bucket_id }
}

/// Obtain an authorization to upload files to a bucket.
///
/// Use the returned [UploadAuthorization] when calling [upload_file].
///
/// For faster uploading, you can obtain multiple authorizations and upload
/// files concurrently.
///
/// The `UploadAuthorization` is valid for 24 hours or until an upload attempt
/// is rejected. You can make multiple file uploads with a single authorization.
///
/// The [Authorization] must have [Capability::WriteFiles].
///
/// # B2 API Difference
///
/// The equivalent B2 endpoint is called
/// [`b2_get_upload_url`](https://www.backblaze.com/b2/docs/b2_get_upload_url.html).
pub async fn get_upload_authorization<'a, 'b, C, E>(
    auth: &'a mut Authorization<C>,
    bucket: &'b Bucket,
) -> Result<UploadAuthorization<'a, C, E>, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    get_upload_authorization_by_id(auth, &bucket.bucket_id).await
}

/// Obtain an authorization to upload files to a bucket.
///
/// See [get_upload_authorization] for documentation on retrieving the
/// authorization.
pub async fn get_upload_authorization_by_id<'a, 'b, C, E>(
    auth: &'a mut Authorization<C>,
    bucket_id: impl AsRef<str>,
) -> Result<UploadAuthorization<'a, C, E>, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    use serde_json::json;

    require_capability!(auth, Capability::WriteFiles);

    let res = auth.client.post(auth.api_url("b2_get_upload_url"))
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token).unwrap()
        .with_body_json(json!({ "bucketId": bucket_id.as_ref() }))
        .send().await?;

    let upload_auth: B2Result<UploadAuthorization<'_, _, _>> =
        serde_json::from_slice(&res)?;

    upload_auth.map(move |mut a| { a.auth = Some(auth); a }).into()
}

/// Hide a file so that it cannot be downloaded by name.
///
/// Previous versions of the file are still stored. See
/// <https://www.backblaze.com/b2/docs/file_versions.html> for information on
/// hiding files.
///
/// # Notes
///
/// Some  of the returned [File] fields are empty, `0`, or meaningless for
/// hidden files, such as [content_length](File::content_length) and
/// [sha1_checksum](File::sha1_checksum).
///
/// See <https://www.backblaze.com/b2/docs/b2_hide_file.html> for further
/// information.
pub async fn hide_file<C, E>(auth: &mut Authorization<C>, file: &File)
-> Result<File, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    hide_file_by_name(auth, &file.bucket_id, &file.file_name).await
}

/// Hide a file so that it cannot be downloaded by name.
///
/// Previous versions of the file are still stored. See
/// <https://www.backblaze.com/b2/docs/file_versions.html> for information on
/// hiding files.
///
/// # Notes
///
/// Some  of the returned [File] fields are empty, `0`, or meaningless for
/// hidden files, such as [content_length](File::content_length) and
/// [sha1_checksum](File::sha1_checksum).
///
/// See <https://www.backblaze.com/b2/docs/b2_hide_file.html> for further
/// information.
pub async fn hide_file_by_name<C, E>(
    auth: &mut Authorization<C>,
    bucket_id: impl AsRef<str>,
    file_name: impl AsRef<str>,
) -> Result<File, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    use serde_json::json;

    require_capability!(auth, Capability::WriteFiles);

    let res = auth.client.post(auth.api_url("b2_hide_file"))
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token).unwrap()
        .with_body_json(json!({
            "bucketId": bucket_id.as_ref(),
            "fileName": file_name.as_ref(),
        }))
        .send().await?;

    let file: B2Result<File> = serde_json::from_slice(&res)?;
    file.into()
}

/// A request to list the names of files stored in a bucket.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)]
pub struct ListFileNames<'a> {
    bucket_id: &'a str,
    start_file_name: Option<String>,
    max_file_count: Option<u16>,
    prefix: Option<&'a str>,
    delimiter: Option<char>,
}

impl<'a> ListFileNames<'a> {
    pub fn builder() -> ListFileNamesBuilder<'a> {
        ListFileNamesBuilder::default()
    }
}

/// A builder for a [ListFileNames] request.
#[derive(Default)]
pub struct ListFileNamesBuilder<'a> {
    bucket_id: Option<&'a str>,
    start_file_name: Option<String>,
    max_file_count: Option<u16>,
    prefix: Option<&'a str>,
    delimiter: Option<char>,
}

impl<'a> ListFileNamesBuilder<'a> {
    /// The bucket ID from which to list files.
    pub fn bucket_id(mut self, id: &'a str) -> Self {
        self.bucket_id = Some(id);
        self
    }

    /// The file name with which to start the listing.
    pub fn start_file_name(mut self, file_name: impl Into<String>) -> Self {
        self.start_file_name = Some(file_name.into());
        self
    }

    /// The maximum number of files to return.
    ///
    /// The default is 100. The provided `count` will be clamped to a value
    /// between 1 and 10,000 inclusive.
    ///
    /// A single transaction has a limit of 1,000 files; values greater than
    /// 1,000 will incur charges for multiple transactions.
    ///
    /// If more than 10,000 files are needed, a new request must be made.
    pub fn max_file_count(mut self, count: u16) -> Self {
        use std::cmp::Ord as _;

        self.max_file_count = Some(count.clamp(1, 10_000));
        self
    }

    /// Set the filename prefix to filter the file listing.
    ///
    /// If not set, all files are matched.
    ///
    /// See <https://www.backblaze.com/b2/docs/b2_list_file_names.html> for
    /// information on file prefixes and delimiters, and their interaction with
    /// each other.
    pub fn prefix(mut self, prefix: &'a str)
    -> Result<Self, FileNameValidationError> {
        self.prefix = Some(validated_file_name(prefix)?);
        Ok(self)
    }

    /// Set the delimiter to use to simulate a hierarchical filesystem.
    ///
    /// See <https://www.backblaze.com/b2/docs/b2_list_file_names.html> for
    /// information on file prefixes and delimiters, and their interaction with
    /// each other.
    pub fn delimiter(mut self, delimiter: char)
    -> Result<Self, FileNameValidationError> {
        // Because this is for a filename, we're assuming no control characters
        // are allowed. B2 explicitly forbids ASCII control characters; not sure
        // of their UTF support...
        if delimiter.is_ascii_control() {
            Err(FileNameValidationError::InvalidChar(delimiter))
        } else {
            self.delimiter = Some(delimiter);
            Ok(self)
        }
    }

    /// Build a [ListFileNames] request.
    ///
    /// Returns an error if the bucket ID has not been set.
    pub fn build(self) -> Result<ListFileNames<'a>, MissingData> {
        let bucket_id = self.bucket_id.ok_or_else(||
            MissingData::new("bucket_id")
        )?;

        Ok(ListFileNames {
            bucket_id,
            start_file_name: self.start_file_name,
            max_file_count: self.max_file_count,
            prefix: self.prefix,
            delimiter: self.delimiter,
        })
    }
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct FileNameList {
    files: Vec<File>,
    next_file_name: Option<String>,
}

/// Get a list of file names in a bucket.
///
/// See <https://www.backblaze.com/b2/docs/b2_list_file_names.html> for more
/// information, including setting filename prefixes for filtering and a
/// delimiter for working with virtual folders.
#[allow(clippy::needless_lifetimes)] // False positive.
pub async fn list_file_names<'a, C, E>(
    auth: &mut Authorization<C>,
    request: ListFileNames<'a>,
) -> Result<(Vec<File>, Option<ListFileNames<'a>>), Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    require_capability!(auth, Capability::ListFiles);

    let res = auth.client.post(auth.api_url("b2_list_file_names"))
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token).unwrap()
        .with_body_json(serde_json::to_value(&request)?)
        .send().await?;

    let files: B2Result<FileNameList> = serde_json::from_slice(&res)?;
    match files {
        B2Result::Ok(files) => {
            if let Some(next_file) = files.next_file_name {
                let mut request = request;
                request.start_file_name = Some(next_file);

                Ok((files.files, Some(request)))
            } else {
                Ok((files.files, None))
            }
        },
        B2Result::Err(e) => Err(e.into()),
    }
}

/// A request to list the names of files stored in a bucket.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)]
pub struct ListFileVersions<'a> {
    bucket_id: &'a str,
    start_file_name: Option<String>,
    start_file_id: Option<String>,
    max_file_count: Option<u16>,
    prefix: Option<&'a str>,
    delimiter: Option<char>,
}

impl<'a> ListFileVersions<'a> {
    pub fn builder() -> ListFileVersionsBuilder<'a> {
        ListFileVersionsBuilder::default()
    }
}

/// A builder for a [ListFileVersions] request.
#[derive(Default)]
pub struct ListFileVersionsBuilder<'a> {
    bucket_id: Option<&'a str>,
    start_file_name: Option<String>,
    start_file_id: Option<String>,
    max_file_count: Option<u16>,
    prefix: Option<&'a str>,
    delimiter: Option<char>,
}

impl<'a> ListFileVersionsBuilder<'a> {
    /// The bucket ID from which to list files.
    pub fn bucket_id(mut self, id: &'a str) -> Self {
        self.bucket_id = Some(id);
        self
    }

    /// The file name with which to start the listing.
    ///
    /// If the file ID is also specified, the name and ID pair is the starting
    /// point of the listing.
    pub fn start_file_name(mut self, file_name: impl Into<String>) -> Self {
        self.start_file_name = Some(file_name.into());
        self
    }

    /// The first file ID to return in the listing.
    ///
    /// If a file ID is provided, then the corresponding filename is required.
    pub fn start_file_id(mut self, file_id: impl Into<String>) -> Self {
        self.start_file_id = Some(file_id.into());
        self
    }

    /// The maximum number of files to return.
    ///
    /// The default is 100. The provided `count` will be clamped to a value
    /// between 1 and 10,000 inclusive.
    ///
    /// A single transaction has a limit of 1,000 files; values greater than
    /// 1,000 will incur charges for multiple transactions.
    ///
    /// If more than 10,000 files are needed, a new request must be made.
    pub fn max_file_count(mut self, count: u16) -> Self {
        use std::cmp::Ord as _;

        self.max_file_count = Some(count.clamp(1, 10_000));
        self
    }

    /// Set the filename prefix to filter the file listing.
    ///
    /// If not set, all files are matched.
    ///
    /// See <https://www.backblaze.com/b2/docs/b2_list_file_names.html> for
    /// information on file prefixes and delimiters, and their interaction with
    /// each other.
    pub fn prefix(mut self, prefix: &'a str)
    -> Result<Self, FileNameValidationError> {
        self.prefix = Some(validated_file_name(prefix)?);
        Ok(self)
    }

    /// Set the delimiter to use to simulate a hierarchical filesystem.
    ///
    /// See <https://www.backblaze.com/b2/docs/b2_list_file_names.html> for
    /// information on file prefixes and delimiters, and their interaction with
    /// each other.
    pub fn delimiter(mut self, delimiter: char)
    -> Result<Self, FileNameValidationError> {
        // Because this is for a filename, we're assuming no control characters
        // are allowed. B2 explicitly forbids ASCII control characters; not sure
        // of their UTF support...
        if delimiter.is_ascii_control() {
            Err(FileNameValidationError::InvalidChar(delimiter))
        } else {
            self.delimiter = Some(delimiter);
            Ok(self)
        }
    }

    /// Build a [ListFileVersions] request.
    ///
    /// Returns an error if the bucket ID has not been set.
    pub fn build(self) -> Result<ListFileVersions<'a>, MissingData> {
        let bucket_id = self.bucket_id.ok_or_else(||
            MissingData::new("bucket_id")
        )?;

        if self.start_file_id.is_some() && self.start_file_name.is_none() {
            return Err(MissingData::new("start_file_name")
                .with_message(
                    "If start_file_id is specified, start_file_name is required"
                )
            );
        }

        Ok(ListFileVersions {
            bucket_id,
            start_file_name: self.start_file_name,
            start_file_id: self.start_file_id,
            max_file_count: self.max_file_count,
            prefix: self.prefix,
            delimiter: self.delimiter,
        })
    }
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct FileVersionList {
    files: Vec<File>,
    next_file_name: Option<String>,
    next_file_id: Option<String>,
}

/// List all versions of the files contained in a bucket.
///
/// Files are listed in alphabetical order by filename, then by upload timestamp
/// sorted descending.
///
/// See <https://www.backblaze.com/b2/docs/b2_list_file_versions.html> for more
/// information.
#[allow(clippy::needless_lifetimes)] // False positive.
pub async fn list_file_versions<'a, C, E>(
    auth: &mut Authorization<C>,
    request: ListFileVersions<'a>,
) -> Result<(Vec<File>, Option<ListFileVersions<'a>>), Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    require_capability!(auth, Capability::ListFiles);

    let res = auth.client.post(auth.api_url("b2_list_file_versions"))
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token).unwrap()
        .with_body_json(serde_json::to_value(&request)?)
        .send().await?;

    let files: B2Result<FileVersionList> = serde_json::from_slice(&res)?;
    match files {
        B2Result::Ok(files) => {
            let mut request = request;

            if files.next_file_name.is_some() {
                request.start_file_name = files.next_file_name;
                request.start_file_id = files.next_file_id;

                Ok((files.files, Some(request)))
            } else {
                Ok((files.files, None))
            }
        },
        B2Result::Err(e) => Err(e.into()),
    }
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ListFileParts<'a> {
    file_id: &'a str,
    start_part_number: Option<u16>,
    max_part_count: Option<u16>,
}

impl<'a> ListFileParts<'a> {
    pub fn builder() -> ListFilePartsBuilder<'a> {
        ListFilePartsBuilder::default()
    }
}

#[derive(Default)]
pub struct ListFilePartsBuilder<'a> {
    file_id: Option<&'a str>,
    start_part_number: Option<u16>,
    max_part_count: Option<u16>,
}

impl<'a> ListFilePartsBuilder<'a> {
    /// A [File] returned by [start_large_file].
    pub fn file(mut self, file: &'a File) -> Self {
        self.file_id = Some(&file.file_id);
        self
    }

    /// The ID of a [File] returned by [start_large_file].
    pub fn file_id(mut self, id: &'a str) -> Self {
        self.file_id = Some(id);
        self
    }

    /// The first part to return in the listing.
    pub fn start_part_number(mut self, num: u16) -> Self {
        self.start_part_number = Some(num);
        self
    }

    /// The maximum number of parts to return.
    ///
    /// The default is 100. The provided `count` will be clamped to a value
    /// between 1 and 1,000 inclusive.
    ///
    /// If more than 1,000 parts are needed, a new request must be made.
    pub fn max_part_count(mut self, count: u16) -> Self {
        use std::cmp::Ord as _;

        self.max_part_count = Some(count.clamp(1, 1_000));
        self
    }

    pub fn build(self) -> Result<ListFileParts<'a>, MissingData> {
        let file_id = self.file_id.ok_or_else(||
            MissingData::new("file_id")
        )?;

        Ok(ListFileParts {
            file_id,
            start_part_number: self.start_part_number,
            max_part_count: self.max_part_count,
        })
    }
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct FilePartList {
    parts: Vec<FilePart>,
    next_part_number: Option<u16>,
}

/// List the parts of a large file that has not yet been completed.
#[allow(clippy::needless_lifetimes)] // False positive.
pub async fn list_file_parts<'a, C, E>(
    auth: &mut Authorization<C>,
    request: ListFileParts<'a>,
) -> Result<(Vec<FilePart>, Option<ListFileParts<'a>>), Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    require_capability!(auth, Capability::WriteFiles);

    let res = auth.client.post(auth.api_url("b2_list_parts"))
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token).unwrap()
        .with_body_json(serde_json::to_value(&request)?)
        .send().await?;

    let parts: B2Result<FilePartList> = serde_json::from_slice(&res)?;
    match parts {
        B2Result::Ok(parts) => {
            if let Some(next_part) = parts.next_part_number {
                let mut request = request;
                request.start_part_number = Some(next_part);

                Ok((parts.parts, Some(request)))
            } else {
                Ok((parts.parts, None))
            }
        },
        B2Result::Err(e) => Err(e.into()),
    }
}

#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
#[allow(dead_code)]
pub struct ListUnfinishedLargeFiles<'a> {
    bucket_id: &'a str,
    name_prefix: Option<&'a str>,
    start_file_id: Option<String>,
    max_file_count: Option<u16>,
}

impl<'a> ListUnfinishedLargeFiles<'a> {
    pub fn builder() -> ListUnfinishedLargeFilesBuilder<'a> {
        ListUnfinishedLargeFilesBuilder::default()
    }
}

#[derive(Default)]
pub struct ListUnfinishedLargeFilesBuilder<'a> {
    bucket_id: Option<&'a str>,
    name_prefix: Option<&'a str>,
    start_file_id: Option<String>,
    max_file_count: Option<u16>,
}

impl<'a> ListUnfinishedLargeFilesBuilder<'a> {
    /// The bucket ID from which to list files.
    pub fn bucket_id(mut self, id: &'a str) -> Self {
        self.bucket_id = Some(id);
        self
    }

    /// Set the filename prefix to filter the file listing.
    ///
    /// If not set, all files are matched.
    pub fn prefix(mut self, prefix: &'a str)
    -> Result<Self, FileNameValidationError> {
        self.name_prefix = Some(validated_file_name(prefix)?);
        Ok(self)
    }

    /// The file ID with which to start the listing.
    pub fn start_file_id(mut self, file_id: impl Into<String>) -> Self {
        self.start_file_id = Some(file_id.into());
        self
    }

    /// The maximum number of files to return.
    ///
    /// The default is 100. The provided `count` will be clamped to a value
    /// between 1 and 100 inclusive.
    ///
    /// If more than 100 files are needed, a new request must be made.
    pub fn max_file_count(mut self, count: u16) -> Self {
        use std::cmp::Ord as _;

        self.max_file_count = Some(count.clamp(1, 10_000));
        self
    }

    /// Create a [ListUnfinishedLargeFiles] request.
    pub fn build(self) -> Result<ListUnfinishedLargeFiles<'a>, MissingData> {
        let bucket_id = self.bucket_id.ok_or_else(||
            MissingData::new("bucket_id")
        )?;

        Ok(ListUnfinishedLargeFiles {
            bucket_id,
            name_prefix: self.name_prefix,
            start_file_id: self.start_file_id,
            max_file_count: self.max_file_count,
        })
    }
}

#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct FileIdList {
    files: Vec<File>,
    next_file_id: Option<String>,
}

/// Get a list of the unfinished large files stored by B2.
///
/// If there are more files, returns a [ListUnfinishedLargeFiles] request that
/// will begin with the next file.
///
/// See <https://www.backblaze.com/b2/docs/b2_list_unfinished_large_files.html>
/// for further information.
#[allow(clippy::needless_lifetimes)] // False positive.
pub async fn list_unfinished_large_files<'a, C, E>(
    auth: &mut Authorization<C>,
    request: ListUnfinishedLargeFiles<'a>
) -> Result<(Vec<File>, Option<ListUnfinishedLargeFiles<'a>>), Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    require_capability!(auth, Capability::ListFiles);

    let res = auth.client.post(auth.api_url("b2_list_unfinished_large_files"))
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token).unwrap()
        .with_body_json(serde_json::to_value(&request)?)
        .send().await?;

    let files: B2Result<FileIdList> = serde_json::from_slice(&res)?;
    match files {
        B2Result::Ok(files) => {
            if let Some(next_file_id) = files.next_file_id {
                let mut request = request;
                request.start_file_id = Some(next_file_id);

                Ok((files.files, Some(request)))
            } else {
                Ok((files.files, None))
            }
        },
        B2Result::Err(e) => Err(e.into()),
    }
}

/// A request to prepare to upload a large file.
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct StartLargeFile<'a> {
    bucket_id: &'a str,
    file_name: String,
    content_type: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    file_info: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    file_retention: Option<FileRetentionPolicy>,
    #[serde(skip_serializing_if = "Option::is_none")]
    legal_hold: Option<LegalHoldValue>,
    #[serde(skip_serializing_if = "Option::is_none")]
    server_side_encryption: Option<ServerSideEncryption>,
}

impl<'a> StartLargeFile<'a> {
    pub fn builder() -> StartLargeFileBuilder<'a> {
        StartLargeFileBuilder::default()
    }
}

/// A builder for a [StartLargeFile] request.
#[derive(Debug, Default)]
pub struct StartLargeFileBuilder<'a> {
    bucket_id: Option<&'a str>,
    file_name: Option<String>,
    content_type: Option<String>,
    file_info: Option<serde_json::Value>,
    file_retention: Option<FileRetentionPolicy>,
    legal_hold: Option<LegalHoldValue>,
    server_side_encryption: Option<ServerSideEncryption>,

    // To merge into file_info on build:
    last_modified: Option<i64>,
    sha1_checksum: Option<&'a str>,
    content_disposition: Option<String>,
    content_language: Option<String>,
    expires: Option<String>,
    cache_control: Option<String>,
    content_encoding: Option<String>,
}

impl<'a> StartLargeFileBuilder<'a> {
    /// Specify the bucket in which to store the new file.
    pub fn bucket_id(mut self, id: &'a str) -> Self {
        self.bucket_id = Some(id);
        self
    }

    /// Set the file's name.
    ///
    /// The provided name will be percent-encoded.
    pub fn file_name(mut self, name: impl AsRef<str>)
    -> Result<Self, FileNameValidationError> {
        let name = validated_file_name(name.as_ref())?;

        self.file_name = Some(percent_encode!(name));
        Ok(self)
    }

    /// Set the file's MIME type.
    ///
    /// If not specified, B2 will attempt to determine the file's type.
    pub fn content_type(mut self, mime: impl Into<String>) -> Self {
        // TODO: B2 has a map of auto-detected MIME types:
        // https://www.backblaze.com/b2/docs/content-types.html
        // How do we want to deal with that?
        self.content_type = Some(mime.into());
        self
    }

    /// Set file metadata to be returned in headers when downloading the file.
    ///
    /// For the following headers, use their corresponding methods instead of
    /// setting the values here:
    ///
    /// * X-Bz-Info-src_last_modified_millis:
    ///   [last_modified](Self::last_modified)
    /// * X-Bz-Info-large_file_sha1: [sha1_checksum](Self::sha1_checksum)
    /// * Content-Disposition: [content_disposition](Self::content_disposition)
    /// * Content-Language: [content_language](Self::content_language)
    /// * Expires: [expiration](Self::expiration)
    /// * Cache-Control: [cache_control](Self::cache_control)
    /// * Content-Encoding: [content_encoding](Self::content_encoding)
    ///
    /// If any of the above are set here and via their methods, the value from
    /// the method will override the value specified here.
    pub fn file_info(mut self, info: serde_json::Value)
    -> Result<Self, ValidationError> {
        self.file_info = Some(validated_file_info(info)?);
        Ok(self)
    }

    /// Set the retention policy for the file.
    pub fn file_retention(mut self, policy: FileRetentionPolicy) -> Self {
        self.file_retention = Some(policy);
        self
    }

    /// Enable a legal hold on the file.
    pub fn with_legal_hold(mut self) -> Self {
        self.legal_hold = Some(LegalHoldValue::On);
        self
    }

    /// Disable a legal hold on the file.
    pub fn without_legal_hold(mut self) -> Self {
        self.legal_hold = Some(LegalHoldValue::Off);
        self
    }

    /// Set the server-side encryption configuration for the file.
    pub fn encryption_settings(mut self, settings: ServerSideEncryption) -> Self
    {
        self.server_side_encryption = Some(settings);
        self
    }

    /// The time of the file's last modification.
    pub fn last_modified(mut self, time: chrono::DateTime<chrono::Utc>) -> Self
    {
        self.last_modified = Some(time.timestamp_millis());
        self
    }

    /// The SHA1 checksum of the file's contents.
    ///
    /// B2 will use this to verify the accuracy of the file upload, and it will
    /// be returned in the header `X-Bz-Content-Sha1` when downloading the file.
    pub fn sha1_checksum(mut self, checksum: &'a str) -> Self {
        self.sha1_checksum = Some(checksum);
        self
    }

    /// The value to use for the `Content-Disposition` header when downloading
    /// the file.
    ///
    /// Parameter continuations are not supported.
    ///
    /// Note that the download request can override this value.
    pub fn content_disposition(mut self, disposition: ContentDisposition)
    -> Result<Self, ValidationError> {
        validate_content_disposition(&disposition.0, false)?;

        self.content_disposition = Some(percent_encode!(disposition.0));
        Ok(self)
    }

    /// The value to use for the `Content-Language` header when downloading the
    /// file.
    ///
    /// Note that the download request can override this value.
    pub fn content_language(mut self, language: impl Into<String>) -> Self {
        // TODO: validate content_language
        self.content_language = Some(percent_encode!(language.into()));
        self
    }

    /// The value to use for the `Expires` header when the file is downloaded.
    ///
    /// Note that the download request can override this value.
    pub fn expiration(mut self, expiration: Expires) -> Self {
        let expires = percent_encode!(expiration.value().to_string());

        self.expires = Some(expires);
        self
    }

    /// The value to use for the `Cache-Control` header when the file is
    /// downloaded.
    ///
    /// This would override the value set at the bucket level, and can be
    /// overriden by a download request.
    pub fn cache_control(mut self, cache_control: CacheControl) -> Self {
        self.cache_control = Some(cache_control.value().to_string());
        self
    }

    /// The value to use for the `Content-Encoding` header when the file is
    /// downloaded.
    ///
    /// Note that this can be overriden by a download request.
    pub fn content_encoding(mut self, encoding: ContentEncoding) -> Self {
        let encoding = percent_encode!(format!("{}", encoding.encoding()));
        self.content_encoding = Some(encoding);
        self
    }

    pub fn build(self) -> Result<StartLargeFile<'a>, ValidationError> {
        let bucket_id = self.bucket_id.ok_or_else(||
            ValidationError::MissingData(
                "The bucket ID in which to store the file must be present"
                    .into()
            )
        )?;

        let file_name = self.file_name.ok_or_else(||
            ValidationError::MissingData(
                "The file name must be specified".into()
            )
        )?;

        let content_type = self.content_type
            .unwrap_or_else(|| "b2/x-auto".into());

        let file_info = if let Some(mut file_info) = self.file_info {
            let info_map = file_info.as_object_mut()
                .expect("file_info is not a JSON object");

            add_file_info!(info_map, "src_last_modified_millis",
                self.last_modified.map(|v| v.to_string()));
            add_file_info!(info_map, "large_file_sha1", self.sha1_checksum);
            add_file_info!(info_map, "b2-content-disposition",
                self.content_disposition);
            add_file_info!(info_map, "b2-content-language",
                self.content_language);
            add_file_info!(info_map, "b2-expires", self.expires);
            add_file_info!(info_map, "b2-cache-control", self.cache_control);
            add_file_info!(info_map, "b2-content-encoding",
                self.content_encoding);

            Some(file_info)
        } else {
            None
        };

        validate_file_metadata_size(
            &file_name,
            file_info.as_ref(),
            self.server_side_encryption.as_ref()
        )?;

        Ok(StartLargeFile {
            bucket_id,
            file_name,
            content_type,
            file_info,
            file_retention: self.file_retention,
            legal_hold: self.legal_hold,
            server_side_encryption: self.server_side_encryption,
        })
    }
}

/// Prepare to upload a large file in multiple parts.
///
/// After calling `start_large_file`, each thread uploading a file part should
/// call [get_upload_part_authorization] to obtain an upload authorization.
/// Then call [upload_file_part] to upload the relevant file part.
///
/// File parts can be copied from an existing file via [copy_file_part].
///
/// A large file size can be 100 MB to 10 TB (inclusive). See
/// <https://www.backblaze.com/b2/docs/large_files.html> for more information on
/// working with large files.
///
/// There must be at least two parts to a large file, with each part between 5
/// MB to 5 GB inclusive; the final part can be less than 5 MB but must contain
/// at least one byte.
///
/// See <https://www.backblaze.com/b2/docs/b2_start_large_file.html> for the B2
/// documentation on starting large file uploads.
///
/// The [Authorization] must have [Capability::WriteFiles].
// TODO: Return a LargeFile or FileInProgress type? It would only matter for
// something like `copy_file_part` where it provides type-safety when passing
// both a source file and the large (destination) file IDs together.
pub async fn start_large_file<'a, C, E>(
    auth: &mut Authorization<C>,
    file: StartLargeFile<'_>
) -> Result<File, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    require_capability!(auth, Capability::WriteFiles);
    if file.file_retention.is_some() {
        require_capability!(auth, Capability::WriteFileRetentions);
    }
    if file.legal_hold.is_some() {
        require_capability!(auth, Capability::WriteFileLegalHolds);
    }
    if file.server_side_encryption.is_some() {
        require_capability!(auth, Capability::WriteBucketEncryption);
    }

    let res = auth.client.post(auth.api_url("b2_start_large_file"))
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token).unwrap()
        .with_body_json(serde_json::to_value(file)?)
        .send().await?;

    let file: B2Result<File> = serde_json::from_slice(&res)?;
    file.into()
}

/// A request to enable or disable a legal hold on a specific file.
#[derive(Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateFileLegalHold<'a> {
    file_name: &'a str,
    file_id: &'a str,
    legal_hold: LegalHoldValue,
}

impl<'a> UpdateFileLegalHold<'a> {
    /// Create a request to enable a legal hold for the specified file.
    pub fn enable_for(file: &'a File) -> Self {
        Self {
            file_name: &file.file_name,
            file_id: &file.file_id,
            legal_hold: LegalHoldValue::On,
        }
    }

    /// Create a request to disable a legal hold for the specified file.
    pub fn disable_for(file: &'a File) -> Self {
        Self {
            file_name: &file.file_name,
            file_id: &file.file_id,
            legal_hold: LegalHoldValue::Off,
        }
    }

    /// Use a builder to create a legal hold update request.
    pub fn builder() -> UpdateFileLegalHoldBuilder<'a> {
        UpdateFileLegalHoldBuilder::default()
    }
}

/// A builder for an [UpdateFileLegalHold] request.
#[derive(Default)]
pub struct UpdateFileLegalHoldBuilder<'a> {
    file_name: Option<&'a str>,
    file_id: Option<&'a str>,
    legal_hold: Option<LegalHoldValue>,
}

impl<'a> UpdateFileLegalHoldBuilder<'a> {
    /// Update the legal hold status for the specified file.
    pub fn file(mut self, file: &'a File) -> Self {
        self.file_name = Some(&file.file_name);
        self.file_id = Some(&file.file_id);
        self
    }

    /// Update the legal hold status for a file with the specified name.
    ///
    /// Setting the [file_id](Self::file_id) is also required.
    pub fn file_name(mut self, file_name: &'a str)
    -> Result<Self, FileNameValidationError> {
        self.file_name = Some(validated_file_name(file_name)?);
        Ok(self)
    }

    /// Update the legal hold status for a file with the specified ID.
    ///
    /// Setting the [file_name](Self::file_name) is also required.
    pub fn file_id(mut self, file_id: &'a str) -> Self {
        self.file_id = Some(file_id);
        self
    }

    /// Enable a legal hold.
    pub fn with_legal_hold(mut self) -> Self {
        self.legal_hold = Some(LegalHoldValue::On);
        self
    }

    /// Disable a legal hold.
    pub fn without_legal_hold(mut self) -> Self {
        self.legal_hold = Some(LegalHoldValue::Off);
        self
    }

    /// Build an [UpdateFileLegalHold] request.
    ///
    /// Returns an error if any of the file name, file ID, or legal hold status
    /// are not specified.
    pub fn build(self) -> Result<UpdateFileLegalHold<'a>, MissingData> {
        let file_name = self.file_name.ok_or_else(||
            MissingData::new("file_name")
        )?;
        let file_id = self.file_id.ok_or_else(||
            MissingData::new("file_id")
        )?;
        let legal_hold = self.legal_hold.ok_or_else(||
            MissingData::new("legal_hold")
        )?;

        Ok(UpdateFileLegalHold {
            file_name,
            file_id,
            legal_hold,
        })
    }
}

// TODO: B2 returns the same data we sent it. Not sure there's a reason to do
// the same - change or continue returning ()?
/// Enable or disable a legal hold on a file.
pub async fn update_file_legal_hold<C, E>(
    auth: &mut Authorization<C>,
    file_update: UpdateFileLegalHold<'_>
) -> Result<(), Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    require_capability!(auth, Capability::WriteFileLegalHolds);

    let res = auth.client.post(auth.api_url("b2_update_file_legal_hold"))
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token).unwrap()
        .with_body_json(serde_json::to_value(file_update)?)
        .send().await?;

    let res: B2Result<UpdateFileLegalHold> = serde_json::from_slice(&res)?;
    res.map(|_| ()).into()
}

/// A request to update file retention settings on a file.
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct UpdateFileRetention<'a> {
    file_name: &'a str,
    file_id: &'a str,
    file_retention: FileRetentionSetting,
    #[serde(skip_serializing_if = "Option::is_none")]
    bypass_governance: Option<BypassGovernance>,
}

impl<'a> UpdateFileRetention<'a> {
    pub fn builder() -> UpdateFileRetentionBuilder<'a> {
        UpdateFileRetentionBuilder::default()
    }
}

/// A builder for an [UpdateFileRetention] request.
#[derive(Default)]
pub struct UpdateFileRetentionBuilder<'a> {
    file_name: Option<&'a str>,
    file_id: Option<&'a str>,
    file_retention: Option<FileRetentionSetting>,
    bypass_governance: Option<BypassGovernance>,
}

impl<'a> UpdateFileRetentionBuilder<'a> {
    /// The file to update.
    pub fn file(mut self, file: &'a File) -> Self {
        self.file_name = Some(&file.file_name);
        self.file_id = Some(&file.file_id);
        self
    }

    /// The name of the file to update.
    ///
    /// The file ID is also required.
    pub fn file_name(mut self, file_name: &'a str)
    -> Result<Self, FileNameValidationError> {
        self.file_name = Some(validated_file_name(file_name)?);
        Ok(self)
    }

    /// The ID of the file to update.
    ///
    /// The file name is also required.
    pub fn file_id(mut self, file_id: &'a str) -> Self {
        self.file_id = Some(file_id);
        self
    }

    /// The new file retention settings for the file.
    ///
    /// See
    /// <https://www.backblaze.com/b2/docs/file_lock.html#b2_api_file_lock_parameters>
    /// for more information.
    pub fn file_retention(mut self, retention: FileRetentionSetting) -> Self {
        self.file_retention = Some(retention);
        self
    }

    /// Bypass governance rules to allow deleting or shortening an existing
    /// governance-mode retention setting.
    ///
    /// The authorization must include [Capability::BypassGovernance].
    pub fn bypass_governance(mut self) -> Self {
        self.bypass_governance = Some(BypassGovernance::Yes);
        self
    }

    /// Create an [UpdateFileRetention] request.
    pub fn build(self) -> Result<UpdateFileRetention<'a>, MissingData> {
        let file_name = self.file_name.ok_or_else(||
            MissingData::new("file_name")
        )?;
        let file_id = self.file_id.ok_or_else(||
            MissingData::new("file_id")
        )?;
        let file_retention = self.file_retention.ok_or_else(||
            MissingData::new("file_retention")
        )?;

        Ok(UpdateFileRetention {
            file_name,
            file_id,
            file_retention,
            bypass_governance: self.bypass_governance,
        })
    }
}

// TODO: B2 returns the same data we sent it. Not sure there's a reason to do
// the same - change or continue returning ()?
/// Modify the file lock retention settings for a file.
///
/// Any attempt to delete or modify a locked file during the retention period
/// will fail.
///
/// The retention settings for files locked with [FileRetentionMode::Governance]
/// can be deleted or shortened only by accounts with
/// [Capability::BypassGovernance].
///
/// The retention settings for files locked with [FileRetentionMode::Compliance]
/// cannot be removed or shortened, but their retention dates can be extended.
///
/// The bucket containing the file must have File Lock enabled.
pub async fn update_file_retention<C, E>(
    auth: &mut Authorization<C>,
    retention_update: UpdateFileRetention<'_>,
) -> Result<(), Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    require_capability!(auth, Capability::WriteFileRetentions);
    if matches!(retention_update.bypass_governance, Some(BypassGovernance::Yes))
    {
        require_capability!(auth, Capability::BypassGovernance);
    }

    let res = auth.client.post(auth.api_url("b2_update_file_retention"))
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token).unwrap()
        .with_body_json(serde_json::to_value(retention_update)?)
        .send().await?;

    let res: B2Result<UpdateFileRetention> = serde_json::from_slice(&res)?;
    res.map(|_| ()).into()
}

/// A request to upload a file to B2.
///
/// Use [UploadFileBuilder] to create an `UploadFile`.
pub struct UploadFile<'a> {
    file_name: String,
    content_type: String,
    sha1_checksum: &'a str,
    file_info: Option<serde_json::Value>,
    legal_hold: Option<LegalHoldValue>,
    file_retention: Option<(FileRetentionMode, i64)>,
    encryption: Option<ServerSideEncryption>,
}

impl<'a> UploadFile<'a> {
    pub fn builder() -> UploadFileBuilder<'a> {
        UploadFileBuilder::default()
    }
}

/// A builder to create an [UploadFile] request.
///
/// The [file_name](Self::file_name), [content_type](Self::content_type), and
/// [sha1_checksum](Self::sha1_checksum) are required.
///
/// The combined length limit of
/// [content_disposition](Self::content_disposition),
/// [content_language](Self::content_language), [expiration](Self::expiration),
/// [cache_control](Self::cache_control),
/// [content_encoding](Self::content_encoding), and custom headers is 7,000
/// bytes, unless self-managed encryption and/or file locks are enabled, in
/// which case the limit is 2,048 bytes.
#[derive(Default)]
pub struct UploadFileBuilder<'a> {
    file_name: Option<String>,
    content_type: Option<String>,
    sha1_checksum: Option<&'a str>,
    last_modified: Option<i64>,
    file_info: Option<serde_json::Value>,

    // To merge into file_info on build.
    content_disposition: Option<String>,
    content_language: Option<String>,
    expires: Option<String>,
    cache_control: Option<String>,
    content_encoding: Option<String>,

    legal_hold: Option<LegalHoldValue>,
    file_retention_mode: Option<FileRetentionMode>,
    file_retention_time: Option<i64>,
    encryption: Option<ServerSideEncryption>,
}

impl<'a> UploadFileBuilder<'a> {
    /// The name of the file.
    ///
    /// The provided name will be percent-encoded.
    pub fn file_name(mut self, name: impl AsRef<str>)
    -> Result<Self, FileNameValidationError> {
        let name = validated_file_name(name.as_ref())?;

        self.file_name = Some(percent_encode!(name));
        Ok(self)
    }

    /// The MIME type of the file's contents.
    ///
    /// This will be returned in the `Content-Type` header when downloading the
    /// file.
    ///
    /// If not specified, B2 will attempt to automatically set the content-type,
    /// defaulting to `application/octet-stream` if unable to determine its
    /// type.
    ///
    /// B2-recognized content-types can be viewed
    /// [here](https://www.backblaze.com/b2/docs/content-types.html)
    pub fn content_type(mut self, content_type: impl Into<Mime>) -> Self {
        self.content_type = Some(content_type.into().to_string());
        self
    }

    /// The SHA1 checksum of the file's contents.
    ///
    /// B2 will use this to verify the accuracy of the file upload, and it will
    /// be returned in the header `X-Bz-Content-Sha1` when downloading the file.
    pub fn sha1_checksum(mut self, checksum: &'a str) -> Self {
        self.sha1_checksum = Some(checksum);
        self
    }

    /// The time of the file's last modification.
    pub fn last_modified(mut self, time: chrono::DateTime<chrono::Utc>) -> Self
    {
        self.last_modified = Some(time.timestamp_millis());
        self
    }

    /// The value to use for the `Content-Disposition` header when downloading
    /// the file.
    ///
    /// Note that the download request can override this value.
    pub fn content_disposition(mut self, disposition: ContentDisposition)
    -> Result<Self, ValidationError> {
        validate_content_disposition(&disposition.0, false)?;

        self.content_disposition = Some(percent_encode!(disposition.0));
        Ok(self)
    }

    /// The value to use for the `Content-Language` header when downloading the
    /// file.
    ///
    /// Note that the download request can override this value.
    pub fn content_language(mut self, language: impl Into<String>) -> Self {
        // TODO: validate content_language
        self.content_language = Some(percent_encode!(language.into()));
        self
    }

    /// The value to use for the `Expires` header when the file is downloaded.
    ///
    /// Note that the download request can override this value.
    pub fn expiration(mut self, expiration: Expires) -> Self {
        let expires = percent_encode!(expiration.value().to_string());

        self.expires = Some(expires);
        self
    }

    /// The value to use for the `Cache-Control` header when the file is
    /// downloaded.
    ///
    /// This would override the value set at the bucket level, and can be
    /// overriden by a download request.
    pub fn cache_control(mut self, cache_control: CacheControl) -> Self {
        self.cache_control = Some(cache_control.value().to_string());
        self
    }

    /// The value to use for the `Content-Encoding` header when the file is
    /// downloaded.
    ///
    /// Note that this can be overriden by a download request.
    pub fn content_encoding(mut self, encoding: ContentEncoding) -> Self {
        let encoding = percent_encode!(format!("{}", encoding.encoding()));
        self.content_encoding = Some(encoding);
        self
    }

    /// Set user-specified file metadata.
    ///
    /// For the following headers, use their corresponding methods instead of
    /// setting the values here:
    ///
    /// * X-Bz-Info-src_last_modified_millis:
    ///   [last_modified](Self::last_modified)
    /// * X-Bz-Info-large_file_sha1: [sha1_checksum](Self::sha1_checksum)
    /// * Content-Disposition: [content_disposition](Self::content_disposition)
    /// * Content-Language: [content_language](Self::content_language)
    /// * Expires: [expiration](Self::expiration)
    /// * Cache-Control: [cache_control](Self::cache_control)
    /// * Content-Encoding: [content_encoding](Self::content_encoding)
    ///
    /// If any of the above are set here and via their methods, the value from
    /// the method will override the value specified here.
    ///
    /// Any header names that do not begin with "`X-Bz-Info-`" will have it
    /// prepended to the supplied name.
    pub fn file_info(mut self, info: serde_json::Value)
    -> Result<Self, ValidationError> {
        let mut file_info = validated_file_info(info)?;

        if let Some(map) = file_info.as_object_mut() {
            let mut key_updates = vec![];

            for key in map.keys() {
                if ! key.starts_with("X-Bz-Info-") {
                    key_updates.push(key.to_owned());
                }
            }

            for old_key in key_updates.into_iter() {
                let val = map.remove(&old_key).unwrap();
                let mut new_key = String::from("X-Bz-Info-");
                new_key.push_str(&old_key);

                map.insert(new_key, val);
            }
        }

        self.file_info = Some(file_info);
        Ok(self)
    }

    /// Set a legal hold on the file.
    pub fn with_legal_hold(mut self) -> Self {
        self.legal_hold = Some(LegalHoldValue::On);
        self
    }

    /// Disable a legal hold on the file.
    pub fn without_legal_hold(mut self) -> Self {
        self.legal_hold = Some(LegalHoldValue::Off);
        self
    }

    /// Set the file retention mode for the file.
    ///
    /// The bucket must be File Lock-enabled and the [Authorization] must have
    /// [Capability::WriteFileRetentions].
    pub fn file_retention_mode(mut self, mode: FileRetentionMode) -> Self {
        self.file_retention_mode = Some(mode);
        self
    }

    /// Set the expiration date and time of a file lock.
    ///
    /// The bucket must be File Lock-enabled and the [Authorization] must have
    /// [Capability::WriteFileRetentions].
    pub fn retain_until(mut self, time: chrono::DateTime<chrono::Utc>)
    -> Self {
        self.file_retention_time = Some(time.timestamp_millis());
        self
    }

    /// Set the encryption settings to use for the file.
    pub fn encryption_settings(mut self, settings: ServerSideEncryption)
    -> Self {
        self.encryption = Some(settings);
        self
    }

    /// Build an [UploadFile] request.
    pub fn build(self) -> Result<UploadFile<'a>, ValidationError> {
        let file_name = self.file_name.ok_or_else(||
            ValidationError::MissingData("Filename is required".into())
        )?;

        let content_type = self.content_type
            .unwrap_or_else(|| "b2/x-auto".into());

        let sha1_checksum = self.sha1_checksum.unwrap_or("do_not_verify");

        if self.file_retention_mode.is_some()
            ^ self.file_retention_time.is_some()
        {
            return Err(ValidationError::BadFormat(
                "File retention policy is not fully configured".into()
            ));
        }

        let file_info = if let Some(mut file_info) = self.file_info {
            let info_map = file_info.as_object_mut()
                .expect("file_info is not a JSON object");

            add_file_info!(info_map, "X-Bz-info-src_last_modified_millis",
                self.last_modified.map(|v| v.to_string()));
            add_file_info!(info_map, "X-Bz-info-b2-content-disposition",
                self.content_disposition);
            add_file_info!(info_map, "X-Bz-info-b2-content-language",
                self.content_language);
            add_file_info!(info_map, "X-Bz-info-b2-expires", self.expires);
            add_file_info!(info_map, "X-Bz-info-b2-content-encoding",
                self.content_encoding);

            Some(file_info)
        } else {
            None
        };

        validate_file_metadata_size(
            &file_name,
            file_info.as_ref(),
            self.encryption.as_ref()
        )?;

        let file_retention = self.file_retention_mode
            .zip(self.file_retention_time);

        Ok(UploadFile {
            file_name,
            content_type,
            sha1_checksum,
            file_info,
            legal_hold: self.legal_hold,
            file_retention,
            encryption: self.encryption,
        })
    }
}

/// Upload a file to a B2 bucket.
///
/// You must first call [get_upload_authorization] to obtain an authorization to
/// upload files to the bucket; then pass that authorization to `upload_file`.
pub async fn upload_file<C, E>(
    auth: &mut UploadAuthorization<'_, C, E>,
    upload: UploadFile<'_>,
    data: &[u8],
) -> Result<File, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    // Unwrap safety: an `UploadAuthorization` can only be created from
    // `get_upload_authorization`, which will always embed an `Authorization`
    // reference before returning.
    let inner_auth = auth.auth.as_mut().unwrap();

    require_capability!(inner_auth, Capability::WriteFiles);

    if upload.file_retention.is_some() {
        // We check this here rather than when we need it below to satisfy the
        // borrow checker.
        require_capability!(inner_auth, Capability::WriteFileRetentions);
    }

    let mut req = inner_auth.client.post(&auth.upload_url)
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token)?
        .with_header("X-Bz-File-Name", &upload.file_name)?
        .with_header("Content-Type", &upload.content_type)?
        .with_header("Content-Length", &data.len().to_string())?
        .with_header("X-Bz-Content-Sha1", upload.sha1_checksum)?;

    if let Some(mut file_info) = upload.file_info {
        let info_map = file_info.as_object_mut()
            .expect("file_info is not a JSON object");

        macro_rules! add_metadata_header {
            ($header_name:literal) => {
                if let Some(val) = info_map.remove($header_name) {
                    req = req.with_header($header_name, val.as_str().unwrap())?
                }
            };
        }

        add_metadata_header!("X-Bz-Info-src_last_modified_millis");
        add_metadata_header!("X-Bz-Info-b2-content-disposition");
        add_metadata_header!("X-Bz-Info-b2-content-language");
        add_metadata_header!("X-Bz-Info-b2-expires");
        add_metadata_header!("X-Bz-Info-b2-cache-control");
        add_metadata_header!("X-Bz-Info-content-encoding");

        for (key, val) in info_map.into_iter() {
            req = req.with_header(key, &val.to_string())?;
        }
    }

    if let Some(legal_hold) = upload.legal_hold {
        req = req.with_header("X-Bz-File-Legal-Hold", &legal_hold.to_string())?;
    }

    if let Some((mode, timestamp)) = upload.file_retention {
        req = req
            .with_header("X-Bz-File-Retention-Mode", &mode.to_string())?
            .with_header("X-Bz-File-Retention-Retain-Until-Timestamp",
                &timestamp.to_string())?;
    }

    if let Some(enc) = upload.encryption {
        if let Some(headers) = enc.to_headers() {
            for (header, value) in headers.into_iter() {
                req = req.with_header(header, &value)?;
            }
        }
    }

    let res = req.with_body(data).send().await?;

    let file: B2Result<File> = serde_json::from_slice(&res)?;
    file.into()
}

/// A request to upload part of a large file.
#[derive(Clone)]
pub struct UploadFilePart<'a> {
    part_number: u16,
    content_sha1: &'a str,
    encryption: Option<ServerSideEncryption>,
}

impl<'a> UploadFilePart<'a> {
    pub fn builder() -> UploadFilePartBuilder<'a> {
        UploadFilePartBuilder::default()
    }

    /// Create a request to upload the next part.
    pub fn create_next_part(mut self, sha1_checksum: Option<&'a str>)
    -> Result<Self, ValidationError> {
        self.content_sha1 = sha1_checksum.unwrap_or("do_not_verify");

        if self.part_number < 10_000 {
            self.part_number += 1;
            Ok(self)
        } else {
            Err(ValidationError::OutOfBounds(
                "The maximum part number is 10,000.".into()
            ))
        }
    }
}

/// A builder for an [UploadFilePart] request.
pub struct UploadFilePartBuilder<'a> {
    part_number: u16,
    content_sha1: &'a str,
    encryption: Option<ServerSideEncryption>,
}

impl<'a> Default for UploadFilePartBuilder<'a> {
    fn default() -> Self {
        Self {
            part_number: 1,
            content_sha1: "do_not_verify",
            encryption: None,
        }
    }
}

impl<'a> UploadFilePartBuilder<'a> {
    /// Set the number of this part.
    ///
    /// Part numbers increment from 1 to 10,000 inclusive and will be clamped to
    /// that range if necessary.
    pub fn part_number(mut self, num: u16) -> Self {
        use std::cmp::Ord as _;

        self.part_number = num.clamp(1, 10_000);
        self
    }

    /// The SHA1 checkum of this part of the file.
    ///
    /// If not provided, the file part will not be immediately verified. The
    /// SHA1 checksums are required to [finish the file
    /// upload](finish_large_file_upload), so they will be verified either when
    /// you upload the part or at the end of the process.
    pub fn part_sha1_checksum(mut self, sha1: &'a str) -> Self {
        self.content_sha1 = sha1;
        self
    }

    /// Set the encryption settings for the source file.
    ///
    /// This must match the settings passed to [start_large_file].
    pub fn server_side_encryption(mut self, encryption: ServerSideEncryption)
    -> Self {
        self.encryption = Some(encryption);
        self
    }

    /// Create an [UploadFilePart] request to pass to [upload_file_part].
    pub fn build(self) -> UploadFilePart<'a> {
        UploadFilePart {
            part_number: self.part_number,
            content_sha1: self.content_sha1,
            encryption: self.encryption,
        }
    }
}

/// Upload a part of a large file to B2.
///
/// Once all parts are uploaded, call [finish_large_file_upload] to merge the
/// parts into a single file.
///
/// If you make two uploads with the same part number, the second upload to
/// complete will overwrite the first.
///
/// The [Authorization] used to create the given [UploadPartAuthorization] must
/// have [Capability::WriteFiles].
///
/// A large file must have at least two parts, and all parts except the last
/// must be at least 5 MB in size. See
/// <https://www.backblaze.com/b2/docs/uploading.html> for further information
/// on uploading files.
///
/// Some errors will requiring obtaining a new [UploadPartAuthorization]. See
/// the B2 documentation for
/// [b2_upload_part](https://www.backblaze.com/b2/docs/b2_upload_part.html) or
/// [uploading files](https://www.backblaze.com/b2/docs/uploading.html) for
/// information on these errors.
///
/// # Parameters
///
/// * `auth`: An upload authorization obtained via
///   [get_upload_part_authorization].
/// * `part_num`: The part number of this part; it must be between 1 and 10,000
///   inclusive and increment by one for each part.
/// * `sha1_checksum`: The SHA1 checksum of this part of the file. You may pass
///   `None` to defer verification until finishing the file.
/// * `data`: The data part of the file.
///
/// Uploading a file part without a checksum is not recommended as it prevents
/// B2 from determining if the file part is corrupt, allowing you to immediately
/// retry.
// TODO: Stream-based data upload to avoid requiring all data be in RAM at once.
pub async fn upload_file_part<C, E>(
    auth: &mut UploadPartAuthorization<'_, '_, C, E>,
    upload: &UploadFilePart<'_>,
    data: &[u8],
) -> Result<FilePart, Error<E>>
    where C: HttpClient<Error=Error<E>>,
          E: fmt::Debug + fmt::Display,
{
    // Unwrap safety: an `UploadPartAuthorization` can only be created from
    // `get_upload_part_authorization`, which will always embed an
    // `Authorization` reference before returning.
    let inner_auth = auth.auth.as_mut().unwrap();

    require_capability!(inner_auth, Capability::WriteFiles);

    let mut req = inner_auth.client.post(&auth.upload_url)
        .expect("Invalid URL")
        .with_header("Authorization", &auth.authorization_token).unwrap()
        .with_header("X-Bz-Part-Number", &upload.part_number.to_string())?
        .with_header("Content-Length", &data.len().to_string())?
        .with_header("X-Bz-Content-Sha1", upload.content_sha1)?;

    if let Some(enc) = &upload.encryption {
        if let Some(headers) = enc.to_headers() {
            for (header, value) in headers.into_iter() {
                req = req.with_header(header, &value)?;
            }
        }
    }

    let res = req.with_body(data).send().await?;

    let part: B2Result<FilePart> = serde_json::from_slice(&res)?;
    part.into()
}

#[cfg(all(test, feature = "with_surf"))]
mod tests_mocked {
    use super::*;
    use crate::{
        account::Capability,
        error::ErrorCode,
        test_utils::{create_test_auth, create_test_client},
    };
    use surf_vcr::VcrMode;


    #[async_std::test]
    async fn start_large_file_upload_success() -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/large_file.yaml",
            None, None
        ).await?;

        let mut auth = create_test_auth(client, vec![Capability::WriteFiles])
            .await;

        let req = StartLargeFile::builder()
            .bucket_id("8d625eb63be2775577c70e1a")
            .file_name("test-large-file")?
            .build()?;

        let file = start_large_file(&mut auth, req).await?;
        assert_eq!(file.file_name(), "test-large-file");
        assert_eq!(file.action(), FileAction::Start);

        Ok(())
    }

    #[async_std::test]
    async fn cancel_large_file_upload_success() -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/large_file.yaml",
            None, None
        ).await?;

        let mut auth = create_test_auth(client, vec![Capability::WriteFiles])
            .await;

        let file_info = cancel_large_file_by_id(
            &mut auth,
            concat!(
                "4_z8d625eb63be2775577c70e1a_f204261ca2ea2c4e1_d20211112",
                "_m211109_c002_v0001114_t0054"
            )
        ).await?;

        assert_eq!(file_info.file_name, "test-large-file");

        Ok(())
    }

    #[async_std::test]
    async fn cancel_large_file_upload_doesnt_exist() -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/large_file.yaml",
            None, None
        ).await?;

        let mut auth = create_test_auth(client, vec![Capability::WriteFiles])
            .await;

        match cancel_large_file_by_id(&mut auth, "bad-id").await.unwrap_err() {
            Error::B2(e) => assert_eq!(e.code(), ErrorCode::BadRequest),
            _ => panic!("Unexpected error type"),
        }

        Ok(())
    }

    #[async_std::test]
    async fn test_get_download_authorization() -> Result<(), anyhow::Error> {
        use http_types::cache::CacheDirective;

        // I need two copies of an identical expiration, but it doesn't
        // implement Clone.
        let (expires1, expires2) = {
            use http_types::Trailers;

            let mut header = Trailers::new();
            header.insert("Expires", "Fri, 21 Jan 2022 14:10:49 GMT");

            let e1 = Expires::from_headers(header.as_ref())
                .unwrap().unwrap().value().to_string();
            let e2 = Expires::from_headers(header.as_ref()).unwrap().unwrap();

            (e1, e2)
        };

        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/auth_account.yaml",
            #[allow(clippy::option_map_unit_fn)]
            Some(Box::new(move |req| {
                use surf_vcr::Body;

                if let Body::Str(body) = &mut req.body {
                    let body_json: Result<serde_json::Value, _> =
                        serde_json::from_str(body);

                    if let Ok(mut body) = body_json {
                        body.get_mut("b2Expires")
                            .map(|v| *v = serde_json::json!(expires1));

                        req.body = Body::Str(body.to_string());
                    }
                }
            })),
            None
        ).await?;

        let mut auth = create_test_auth(client, vec![Capability::ShareFiles])
            .await;

        let mut cache_control = CacheControl::new();
        cache_control.push(CacheDirective::MustRevalidate);

        let req = DownloadAuthorizationRequest::builder()
            .bucket_id("8d625eb63be2775577c70e1a")
            .file_name_prefix("files/")?
            .duration(chrono::Duration::seconds(30))?
            .content_disposition(
                ContentDisposition("Attachment; filename=example.html".into())
            )
            .expiration(expires2)
            .cache_control(cache_control)
            .build()?;

        let download_auth = get_download_authorization(&mut auth, req).await?;
        assert_eq!(download_auth.bucket_id(), "8d625eb63be2775577c70e1a");

        Ok(())
    }

    #[async_std::test]
    async fn test_get_download_authorization_with_only_required_data()
    -> Result<(), anyhow::Error> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/auth_account.yaml",
            None, None
        ).await?;

        let mut auth = create_test_auth(client, vec![Capability::ShareFiles])
            .await;

        let req = DownloadAuthorizationRequest::builder()
            .bucket_id("8d625eb63be2775577c70e1a")
            .file_name_prefix("files/")?
            .duration(chrono::Duration::seconds(30))?
            .build()?;

        let download_auth = get_download_authorization(&mut auth, req).await?;
        assert_eq!(download_auth.bucket_id(), "8d625eb63be2775577c70e1a");

        Ok(())
    }

    #[async_std::test]
    async fn obtain_part_upload_authorization() -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/large_file.yaml",
            None, None
        ).await?;

        let mut auth = create_test_auth(client, vec![Capability::WriteFiles])
            .await;

        let file = StartLargeFile::builder()
            .bucket_id("8d625eb63be2775577c70e1a")
            .file_name("Test-large-file.txt")?
            .content_type("text/plain")
            .build()?;

        let file = start_large_file(&mut auth, file).await?;
        let upload_auth = get_upload_part_authorization(&mut auth, &file)
            .await?;

        assert_eq!(upload_auth.file_id, file.file_id);

        Ok(())
    }

    #[async_std::test]
    async fn obtain_upload_authorization() -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/file.yaml",
            None, None
        ).await?;

        let mut auth = create_test_auth(client, vec![Capability::WriteFiles])
            .await;

        let upload_auth = get_upload_authorization_by_id(
            &mut auth,
            "8d625eb63be2775577c70e1a"
        ).await?;

        assert_eq!(upload_auth.bucket_id, "8d625eb63be2775577c70e1a");

        Ok(())
    }

    #[async_std::test]
    async fn upload_file_success() -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/file.yaml",
            None, None
        ).await?;

        let mut auth = create_test_auth(client, vec![Capability::WriteFiles])
            .await;

        let mut upload_auth = get_upload_authorization_by_id(
            &mut auth,
            "8d625eb63be2775577c70e1a"
        ).await?;

        let file = UploadFile::builder()
            .file_name("test-file-upload.txt")?
            .sha1_checksum("81fe8bfe87576c3ecb22426f8e57847382917acf")
            .build()?;

        let file = upload_file(&mut upload_auth, file, b"abcd").await?;

        assert_eq!(file.action, FileAction::Upload);

        Ok(())
    }

    #[async_std::test]
    async fn copy_file_success() -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/large_file.yaml",
            None, None
        ).await?;

        let mut auth = create_test_auth(
            client,
            vec![Capability::WriteFiles, Capability::ReadFiles]
        ).await;

        let file = CopyFile::builder()
            .source_file_id(concat!(
                "4_z8d625eb63be2775577c70e1a_f111954e3108ff3f6_d20211118_",
                "m151810_c002_v0001168_t0010"
            ))
            .destination_file_name("new-file.txt")?
            .build()?;

        let new_file = copy_file(&mut auth, file).await?;
        assert_eq!(new_file.file_name, "new-file.txt");
        assert_eq!(new_file.action, FileAction::Copy);

        Ok(())
    }

    // TODO: test copy_file with a byte range.

    #[async_std::test]
    async fn copy_file_part_success() -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/large_file.yaml",
            None, None
        ).await?;

        let mut auth = create_test_auth(
            client,
            vec![Capability::WriteFiles, Capability::ReadFiles]
        ).await;

        let file = StartLargeFile::builder()
            .bucket_id("8d625eb63be2775577c70e1a")
            .file_name("Test-large-file2.txt")?
            .content_type("text/plain")
            .build()?;

        let file = start_large_file(&mut auth, file).await?;

        let part1 = CopyFilePart::builder()
            .source_file_id(concat!(
                "4_z8d625eb63be2775577c70e1a_f111954e3108ff3f6_d20211118_",
                "m151810_c002_v0001168_t0010"
            ))
            .destination_large_file(&file)
            .part_number(1)?
            .build()?;

        let part2 = CopyFilePart::builder()
            .source_file_id(concat!(
                "4_z8d625eb63be2775577c70e1a_f111954e3108ff3f6_d20211118_",
                "m151810_c002_v0001168_t0010"
            ))
            .destination_large_file(&file)
            .part_number(2)?
            .range(ByteRange::new(0, 3)?)
            .build()?;

        let part1 = copy_file_part(&mut auth, part1).await?;
        let part2 = copy_file_part(&mut auth, part2).await?;

        assert_eq!(part1.part_number, 1);
        assert_eq!(part2.part_number, 2);

        let _file = cancel_large_file(&mut auth, file).await?;
        Ok(())
    }

    // TODO: File header tests.

    #[async_std::test]
    async fn download_file_by_id_success() -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/file.yaml",
            None, None
        ).await?;

        let mut auth = create_test_auth(client, vec![Capability::ReadFiles])
            .await;

        let req = DownloadFile::with_id(concat!("4_z8d625eb63be2775577c70e1a_f",
            "111954e3108ff3f6_d20211118_m151810_c002_v0001168_t0010"));

        let (file, _headers) = download_file(&mut auth, req).await?;
        assert_eq!(file, b"Some text\n");

        Ok(())
    }

    #[async_std::test]
    async fn download_file_by_name_success() -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/file.yaml",
            None, None
        ).await?;

        let mut auth = create_test_auth(client, vec![Capability::ReadFiles])
            .await;

        let req = DownloadFile::with_name("test-file.txt", "testing-b2-client");

        let (file, _headers) = download_file(&mut auth, req).await?;
        assert_eq!(file, b"Some text\n");

        Ok(())
    }

    #[async_std::test]
    async fn download_file_by_name_via_download_authorization_success()
    -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/file.yaml",
            None, None
        ).await?;

        let mut auth = create_test_auth(
            client,
            vec![Capability::ReadFiles, Capability::ShareFiles]
        ).await;

        let req = DownloadAuthorizationRequest::builder()
            .bucket_id("8d625eb63be2775577c70e1a")
            .file_name_prefix("test")?
            .duration(chrono::Duration::seconds(30))?
            .build()?;

        let mut download_auth = get_download_authorization(
            &mut auth,
            req
        ).await?;

        let req = DownloadFile::with_name("test-file.txt", "testing-b2-client");

        let (file, _headers) = download_file(&mut download_auth, req).await?;
        assert_eq!(file, b"Some text\n");

        Ok(())
    }

    /* TODO: Setup, write these tests.
    #[async_std::test]
    async fn download_file_not_authorized() -> anyhow::Result<()> {
        todo!()
    }

    #[async_std::test]
    async fn download_public_file_without_read_cap() -> anyhow::Result<()> {
        todo!()
    }
    */

    #[async_std::test]
    async fn download_file_range_success() -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/file.yaml",
            None, None
        ).await?;

        let mut auth = create_test_auth(client, vec![Capability::ReadFiles])
            .await;

        let req = DownloadFile::builder()
            .file_name("test-file.txt", "testing-b2-client")
            .range(ByteRange::new(5, 8)?)
            .build()?;

        let (file, _headers) = download_file(&mut auth, req).await?;
        assert_eq!(file, b"text");

        Ok(())
    }

    // TODO: Test download with custom headers.

    #[async_std::test]
    async fn delete_file_success() -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/delete_file.yaml",
            None, None
        ).await?;

        let mut auth = create_test_auth(
            client,
            vec![Capability::DeleteFiles, Capability::WriteFiles]
        ).await;

        let mut upload_auth = get_upload_authorization_by_id(
            &mut auth,
            "8d625eb63be2775577c70e1a"
        ).await?;

        let file = UploadFile::builder()
            .file_name("test-file-upload.txt")?
            .sha1_checksum("81fe8bfe87576c3ecb22426f8e57847382917acf")
            .build()?;

        let file = upload_file(&mut upload_auth, file, b"abcd").await?;


        let _ = delete_file_version(&mut auth, file, BypassGovernance::No)
            .await?;

        Ok(())
    }

    #[async_std::test]
    async fn upload_large_file_full_process() -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/large_file.yaml",
            Some(Box::new(|req| {
                use surf_vcr::Body;

                if let Body::Str(body) = &mut req.body {
                    if body.starts_with("aaaaa") {
                        // We don't need to store 5 MB of nothing for our test.
                        req.body = Body::Str("aaaaa for 5 MB of data".into());
                    }
                }
            })),
            None
        ).await?;

        let mut auth = create_test_auth(client, vec![Capability::WriteFiles])
            .await;

        let file = StartLargeFile::builder()
            .bucket_id("8d625eb63be2775577c70e1a")
            .file_name("Test-large-file.txt")?
            .content_type("text/plain")
            .build()?;

        let file = start_large_file(&mut auth, file).await?;
        let mut upload_auth = get_upload_part_authorization(&mut auth, &file)
            .await?;

        // All but the last part must be at least 5MB.
        let data1: Vec<u8> = [b'a'].iter().cycle().take(5*1024*1024)
            .cloned().collect();

        let upload = UploadFilePart::builder()
            .part_number(1)
            .part_sha1_checksum("61b8d6600ac94d912874f569a9341120f680c9f8")
            .build();


        let _part1 = upload_file_part(&mut upload_auth, &upload, &data1).await?;

        let upload = upload.create_next_part(
            Some("924f61661a3472da74307a35f2c8d22e07e84a4d")
        )?;

        let _part2 = upload_file_part(&mut upload_auth, &upload, b"bcd").await?;

        let file = finish_large_file_upload(
            &mut auth,
            &file,
            &[
                "61b8d6600ac94d912874f569a9341120f680c9f8".into(),
                "924f61661a3472da74307a35f2c8d22e07e84a4d".into(),
            ]
        ).await?;

        assert_eq!(file.action, FileAction::Upload);

        Ok(())
    }

    #[async_std::test]
    async fn test_get_file_info() -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/file.yaml",
            None, None
        ).await?;

        let mut auth = create_test_auth(client, vec![Capability::ReadFiles])
            .await;

        let file_info = get_file_info(
            &mut auth,
            concat!("4_z8d625eb63be2775577c70e1a_f1187926dea44b322_d20211230",
                "_m171512_c002_v0001110_t0055")
        ).await?;

        assert_eq!(
            file_info.content_sha1,
            Some(String::from("81fe8bfe87576c3ecb22426f8e57847382917acf"))
        );

        Ok(())
    }

    #[async_std::test]
    async fn test_hide_file() -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/file.yaml",
            None, None
        ).await?;

        let mut auth = create_test_auth(client, vec![Capability::WriteFiles])
            .await;

        let file = hide_file_by_name(
            &mut auth,
            "8d625eb63be2775577c70e1a",
            "test-file.txt"
        ).await?;

        assert_eq!(file.action, FileAction::Hide);

        Ok(())
    }

    #[async_std::test]
    async fn test_list_file_names() -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/file.yaml",
            None,
            Some(std::boxed::Box::new(move |res| {
                use surf_vcr::Body;

                if let Body::Str(body) = &mut res.body {
                    let body_json: Result<serde_json::Value, _> =
                        serde_json::from_str(body);

                    if let Ok(mut body) = body_json {
                        if let Some(files) = body.get_mut("files") {
                            let files = files.as_array_mut().unwrap();

                            for file in files.iter_mut() {
                                file["accountId"] = serde_json::Value::String(
                                    "hidden account id".into()
                                );
                            }
                        }

                        res.body = Body::Str(body.to_string());
                    }
                }
            }))
        ).await?;

        let mut auth = create_test_auth(client, vec![Capability::ListFiles])
            .await;

        let req = ListFileNames::builder()
            .bucket_id("8d625eb63be2775577c70e1a")
            .max_file_count(5)
            .build().unwrap();

        let (files, next_req) = list_file_names(&mut auth, req).await?;

        assert_eq!(files.len(), 2);
        assert!(next_req.is_none());

        Ok(())
    }

    #[async_std::test]
    async fn test_list_file_versions() -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/file.yaml",
            None,
            Some(std::boxed::Box::new(move |res| {
                use surf_vcr::Body;

                if let Body::Str(body) = &mut res.body {
                    let body_json: Result<serde_json::Value, _> =
                        serde_json::from_str(body);

                    if let Ok(mut body) = body_json {
                        if let Some(files) = body.get_mut("files") {
                            let files = files.as_array_mut().unwrap();

                            for file in files.iter_mut() {
                                file["accountId"] = serde_json::Value::String(
                                    "hidden account id".into()
                                );
                            }
                        }

                        res.body = Body::Str(body.to_string());
                    }
                }
            }))
        ).await?;

        let mut auth = create_test_auth(client, vec![Capability::ListFiles])
            .await;

        let req = ListFileVersions::builder()
            .bucket_id("8d625eb63be2775577c70e1a")
            .max_file_count(5)
            .build().unwrap();

        let (files, next_req) = list_file_versions(&mut auth, req).await?;

        assert_eq!(files.len(), 4);
        assert!(next_req.is_none());

        Ok(())
    }

    #[async_std::test]
    async fn test_list_file_parts() -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/large_file.yaml",
            Some(Box::new(|req| {
                use surf_vcr::Body;

                if let Body::Str(body) = &mut req.body {
                    if body.starts_with("aaaaa") {
                        // We don't need to store 5 MB of nothing for our test.
                        req.body = Body::Str("aaaaa for 5 MB of data".into());
                    }
                }
            })),
            None
        ).await?;

        let mut auth = create_test_auth(client, vec![Capability::WriteFiles])
            .await;

        // We need a large file that hasn't been finished yet.
        let file = {
            let file = StartLargeFile::builder()
                .bucket_id("8d625eb63be2775577c70e1a")
                .file_name("unfinished-file.txt")?
                .content_type("text/plain")
                .build()?;

            let file = start_large_file(&mut auth, file).await?;
            let mut upload_auth = get_upload_part_authorization(
                &mut auth,
                &file
            ).await?;

            // All but the last part must be at least 5MB.
            let data1: Vec<u8> = [b'a'].iter().cycle().take(5*1024*1024)
                .cloned().collect();

            let upload = UploadFilePart::builder()
                .part_sha1_checksum("61b8d6600ac94d912874f569a9341120f680c9f8")
                .build();

            let _part1 = upload_file_part(&mut upload_auth, &upload, &data1)
                .await?;

            let upload = upload.create_next_part(
                Some("924f61661a3472da74307a35f2c8d22e07e84a4d")
            )?;

            let _part2 = upload_file_part(&mut upload_auth, &upload, b"bcd")
                .await?;

            file
        };

        let req = ListFileParts::builder()
            .file_id(&file.file_id)
            .max_part_count(5)
            .build().unwrap();

        let (parts, next_req) = list_file_parts(&mut auth, req).await?;

        assert_eq!(parts.len(), 2);
        assert!(next_req.is_none());

        let _ = cancel_large_file(&mut auth, file).await?;

        Ok(())
    }

    #[async_std::test]
    async fn test_list_unfinished_files() -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/large_file.yaml",
            None,
            Some(std::boxed::Box::new(move |res| {
                use surf_vcr::Body;

                if let Body::Str(body) = &mut res.body {
                    let body_json: Result<serde_json::Value, _> =
                        serde_json::from_str(body);

                    if let Ok(mut body) = body_json {
                        if let Some(files) = body.get_mut("files") {
                            let files = files.as_array_mut().unwrap();

                            for file in files.iter_mut() {
                                file["accountId"] = serde_json::Value::String(
                                    "hidden account id".into()
                                );
                            }
                        }

                        res.body = Body::Str(body.to_string());
                    }
                }
            }))
        ).await?;

        let mut auth = create_test_auth(client, vec![Capability::ListFiles])
            .await;

        let list_files = ListUnfinishedLargeFiles::builder()
            .bucket_id("8d625eb63be2775577c70e1a")
            .build()?;

        let (files, next_req) = list_unfinished_large_files(
            &mut auth,
            list_files
        ).await?;

        assert_eq!(files.len(), 2);
        assert!(next_req.is_none());

        Ok(())
    }

    #[async_std::test]
    async fn test_update_legal_hold() -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/file.yaml",
            None, None
        ).await?;

        let mut auth = create_test_auth(
            client,
            vec![Capability::WriteFileLegalHolds]
        ).await;

        let update = UpdateFileLegalHold::builder()
            .file_name("test-file.txt")?
            .file_id(concat!("4_zcd120e962b02c7a577e70e1a_f100e7b2902e23bf1",
                    "_d20220205_m134630_c002_v0001141_t0007"))
            .with_legal_hold()
            .build()?;

        update_file_legal_hold(&mut auth, update).await?;

        Ok(())
    }

    #[async_std::test]
    async fn test_update_legal_hold_fails_when_not_allowed_by_bucket()
    -> anyhow::Result<()> {
        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/file.yaml",
            None, None
        ).await?;

        let mut auth = create_test_auth(
            client,
            vec![Capability::WriteFileLegalHolds]
        ).await;

        let update = UpdateFileLegalHold::builder()
            .file_name("test-file.txt")?
            .file_id(concat!("4_z8d625eb63be2775577c70e1a_f107f7b2843696d21",
                "_d20220201_m191409_c002_v0001094_t0020"))
            .with_legal_hold()
            .build()?;

        let res = update_file_legal_hold(&mut auth, update).await;
        assert!(res.is_err());

        Ok(())
    }

    #[async_std::test]
    async fn test_update_file_retention_settings()
    -> anyhow::Result<()> {
        use chrono::{Utc, TimeZone as _};

        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/file.yaml",
            None, None
        ).await?;

        let mut auth = create_test_auth(
            client,
            vec![Capability::WriteFileRetentions]
        ).await;

        let retain_until = Utc.ymd(3000, 1, 1).and_hms(0, 0, 0);

        let update = UpdateFileRetention::builder()
            .file_name("test-file.txt")?
            .file_id(concat!("4_zcd120e962b02c7a577e70e1a_f100e7b2902e23bf1",
                "_d20220205_m134630_c002_v0001141_t0007"))
            .file_retention(FileRetentionSetting::new(
                FileRetentionMode::Governance,
                retain_until
            )?)
            .build()?;

        update_file_retention(&mut auth, update).await?;

        Ok(())
    }

    #[async_std::test]
    async fn test_update_file_retention_settings_fails_when_bucket_disallows()
    -> anyhow::Result<()> {
        use chrono::{Utc, TimeZone as _};

        let client = create_test_client(
            VcrMode::Replay,
            "test_sessions/file.yaml",
            None, None
        ).await?;

        let mut auth = create_test_auth(
            client,
            vec![Capability::WriteFileRetentions]
        ).await;

        let retain_until = Utc.ymd(3000, 1, 1).and_hms(0, 0, 0);

        let update = UpdateFileRetention::builder()
            .file_name("test-file.txt")?
            .file_id(concat!("4_z8d625eb63be2775577c70e1a_f107f7b2843696d21",
                "_d20220201_m191409_c002_v0001094_t0020"))
            .file_retention(FileRetentionSetting::new(
                FileRetentionMode::Governance,
                retain_until
            )?)
            .build()?;

        let res = update_file_retention(&mut auth, update).await;
        assert!(res.is_err());

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;


    #[async_std::test]
    async fn copy_file_bad_req_content_type() -> anyhow::Result<()> {
        let file = CopyFile::builder()
            .source_file_id(concat!(
                "4_z8d625eb63be2775577c70e1a_f111954e3108ff3f6_d20211118_",
                "m151810_c002_v0001168_t0010"
            ))
            .destination_file_name("new-file.txt")?
            .content_type("text/plain");

        match file.build().unwrap_err() {
            ValidationError::Incompatible(_) => {},
            e => panic!("Unexpected error type: {}", e),
        }

        Ok(())
    }
}