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
// Copyright 2023 MaidSafe.net limited.
//
// This SAFE Network Software is licensed to you under The General Public License (GPL), version 3.
// Unless required by applicable law or agreed to in writing, the SAFE Network Software distributed
// under the GPL Licence is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. Please review the Licences for the specific language governing
// permissions and limitations relating to use of the SAFE Network Software.

mod file_system;
mod files_map;
mod metadata;
mod realpath;

pub(crate) use files_map::{file_map_for_path, get_file_link_and_metadata};
pub(crate) use metadata::FileMeta;
pub(crate) use realpath::RealPath;

pub use files_map::{FileInfo, FilesMap, FilesMapChange, GetAttr};

// List of files uploaded with details if they were added, updated or removed from FilesContainer
pub type ProcessedFiles = BTreeMap<PathBuf, FilesMapChange>;

const ERROR_MSG_NO_FILES_CONTAINER_FOUND: &str = "No FilesContainer found at this address";
// Type tag to use for the FilesContainer stored on Register
pub(crate) const FILES_CONTAINER_TYPE_TAG: u64 = 1_100;

use crate::{
    app::consts::*, app::nrs::VersionHash, resolver::Range, ContentType, DataType, Error, Result,
    Safe, SafeUrl, XorUrl,
};

use sn_client::{Client, QueriedDataReplicas};

use bytes::{Buf, Bytes};
use file_system::{
    file_system_dir_walk, file_system_single_file, normalise_path_separator, upload_file_to_net,
};
use files_map::add_or_update_file_item;
use relative_path::RelativePath;
use std::{
    collections::{BTreeMap, HashSet},
    iter::FromIterator,
    path::{Path, PathBuf},
    str,
};
use tracing::{debug, info, warn};
use xor_name::XorName;

impl Safe {
    /// # Create an empty `FilesContainer`.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// # use sn_api::Safe;
    /// # let rt = tokio::runtime::Runtime::new().unwrap();
    /// # rt.block_on(async {
    ///     let mut safe = Safe::connected(None, None, None, None).await.unwrap();
    ///     let xorurl = safe.files_container_create().await.unwrap();
    ///     assert!(xorurl.contains("safe://"))
    /// # });
    /// ```
    pub async fn files_container_create(&self) -> Result<XorUrl> {
        // Build a Register creation operation
        let xorurl = self
            .register_create(None, FILES_CONTAINER_TYPE_TAG, ContentType::FilesContainer)
            .await?;

        Ok(xorurl)
    }

    /// # Create a `FilesContainer` containing files uploaded from a local folder.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// # use sn_api::Safe;
    /// # let rt = tokio::runtime::Runtime::new().unwrap();
    /// # rt.block_on(async {
    ///     let mut safe = Safe::connected(None, None, None, None).await.unwrap();
    ///     let (xorurl, _processed_files, _files_map) = safe.files_container_create_from("./testdata", None, true, true).await.unwrap();
    ///     assert!(xorurl.contains("safe://"))
    /// # });
    /// ```
    pub async fn files_container_create_from<P: AsRef<Path>>(
        &self,
        location: P,
        dst: Option<&Path>,
        recursive: bool,
        follow_links: bool,
    ) -> Result<(XorUrl, ProcessedFiles, FilesMap)> {
        // Let's upload the files (if not dry_run) and generate the list of local files paths
        let mut processed_files =
            file_system_dir_walk(self, location.as_ref(), recursive, follow_links).await?;

        // The FilesContainer is stored on a Register
        // and the link to the serialised FilesMap as the entry's value
        let files_map = files_map_create(
            self,
            &mut processed_files,
            location.as_ref(),
            dst,
            follow_links,
        )
        .await?;

        // Create a Register
        let xorurl = self.files_container_create().await?;

        if self.dry_run_mode {
            Ok((xorurl.to_string(), processed_files, files_map))
        } else {
            // Store files map on network
            let files_map_xorurl = self.store_files_map(&files_map).await?;

            let mut reg_url = SafeUrl::from_xorurl(&xorurl)?;

            // Write pointer to files_map onto our register
            let reg_address = self.get_register_address(&reg_url)?;
            let entry = files_map_xorurl.as_bytes().to_vec();
            let client = self.get_safe_client()?;
            let (entry_hash, reg_op) = client
                .write_to_local_register(reg_address, entry, Default::default())
                .await?;

            client.publish_register_ops(reg_op).await?;

            // We return versioned xorurl
            reg_url.set_content_version(Some(VersionHash::from(&entry_hash)));

            Ok((reg_url.to_string(), processed_files, files_map))
        }
    }

    /// # Fetch an existing `FilesContainer`.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// # use sn_api::Safe;
    /// # let rt = tokio::runtime::Runtime::new().unwrap();
    /// # rt.block_on(async {
    /// #   let safe = Safe::connected(None, None, None, None).await.unwrap();
    ///     let (xorurl, _processed_files, _files_map) = safe.files_container_create_from("./testdata", None, true, true).await.unwrap();
    ///     let (version, files_map) = safe.files_container_get(&xorurl).await.unwrap().unwrap();
    ///     println!("FilesContainer fetched is at version: {}", version);
    ///     println!("FilesMap of fetched version is: {:?}", files_map);
    /// # });
    /// ```
    pub async fn files_container_get(&self, url: &str) -> Result<Option<(VersionHash, FilesMap)>> {
        debug!("Getting files container from: {:?}", url);
        let safe_url = self.parse_and_resolve_url(url).await?;

        self.fetch_files_container(&safe_url).await
    }

    /// Fetch a `FilesContainer` from a `SafeUrl` without performing any type of URL resolution
    pub(crate) async fn fetch_files_container(
        &self,
        safe_url: &SafeUrl,
    ) -> Result<Option<(VersionHash, FilesMap)>> {
        // fetch register entries and wrap errors
        debug!(
            "Fetching FilesContainer from {}, address type: {:?}",
            safe_url,
            safe_url.address()
        );

        let entries = self
            .register_fetch_entries(safe_url)
            .await
            .map_err(|e| match e {
                Error::ContentNotFound(_) => {
                    Error::ContentNotFound(ERROR_MSG_NO_FILES_CONTAINER_FOUND.to_string())
                }
                Error::HashNotFound(_) => Error::VersionNotFound(format!(
                    "Version '{}' is invalid for FilesContainer found at \"{}\"",
                    match safe_url.content_version() {
                        Some(v) => v.to_string(),
                        None => "None".to_owned(),
                    },
                    safe_url
                )),
                err => Error::NetDataError(format!("Failed to get current version: {err}")),
            })?;

        // take the 1st entry (TODO Multiple entries)
        debug!(
            "Retrieved {} entries for register at {}",
            entries.len(),
            safe_url.to_string()
        );
        if entries.len() > 1 {
            return Err(Error::NotImplementedError("Multiple file container entries not managed, this happends when 2 clients write concurrently to a file container".to_string()));
        }
        let first_entry = entries.iter().next();
        let (version, files_map_xorurl) = if let Some((v, m)) = first_entry {
            (v.into(), str::from_utf8(m)?)
        } else {
            warn!("FilesContainer found at \"{:?}\" was empty", safe_url);
            return Ok(None);
        };

        // Using the FilesMap XOR-URL we can now fetch the FilesMap and deserialise it
        let files_map_url = SafeUrl::from_xorurl(files_map_xorurl)?;
        let serialised_files_map = self.fetch_data(&files_map_url, None).await?;
        let files_map = serde_json::from_slice(serialised_files_map.chunk()).map_err(|err| {
            Error::ContentError(format!(
                "Couldn't deserialise the FilesMap stored in the FilesContainer: {err:?}"
            ))
        })?;
        debug!("Files map retrieved.... {:?}", &version);

        Ok(Some((version, files_map)))
    }

    /// # Sync up local folder with the content on a `FilesContainer`.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// # use sn_api::Safe;
    /// # let rt = tokio::runtime::Runtime::new().unwrap();
    /// # rt.block_on(async {
    /// #   let safe = Safe::connected(None, None, None, None).await.unwrap();
    ///     let (xorurl, _processed_files, _files_map) = safe.files_container_create_from("./testdata", None, true, false).await.unwrap();
    ///     let (optional_version_map, new_processed_files) = safe.files_container_sync("./testdata", &xorurl, true, true, false, false).await.unwrap();
    ///     if let Some((version, new_files_map)) = optional_version_map {
    ///         println!("FilesContainer is now at version: {}", version);
    ///         println!("The local files that were synced up are: {:?}", new_processed_files);
    ///         println!("The FilesMap of the updated FilesContainer now is: {:?}", new_files_map);
    ///     }
    /// # });
    /// ```
    #[allow(clippy::too_many_arguments)]
    pub async fn files_container_sync<P: AsRef<Path>>(
        &self,
        location: P,
        url: &str,
        recursive: bool,
        follow_links: bool,
        delete: bool,
        update_nrs: bool,
    ) -> Result<(Option<(VersionHash, FilesMap)>, ProcessedFiles)> {
        if delete && !recursive {
            return Err(Error::InvalidInput(
                "'delete' is not allowed if 'recursive' is not set".to_string(),
            ));
        }

        let safe_url = SafeUrl::from_url(url)?;

        // If NRS name shall be updated then the URL has to be an NRS-URL
        if update_nrs && safe_url.content_type() != ContentType::NrsMapContainer {
            return Err(Error::InvalidInput(
                "'update-nrs' is not allowed since the URL provided is not an NRS URL".to_string(),
            ));
        }

        let mut safe_url = self.parse_and_resolve_url(url).await?;

        // If the FilesContainer URL was resolved from an NRS name we need to remove
        // the version from it so we can fetch latest version of it for sync-ing
        safe_url.set_content_version(None);

        let (current_version, current_files_map) =
            match self.fetch_files_container(&safe_url).await? {
                Some((version, files_map)) => (Some(version), files_map),
                None => (None, FilesMap::default()),
            };

        // Let's generate the list of local files paths, without uploading any new file yet.
        // Use a dry runner only for this next operation
        let dry_runner = Safe::dry_runner(Some(self.xorurl_base));
        let processed_files =
            file_system_dir_walk(&dry_runner, location.as_ref(), recursive, follow_links).await?;

        let dst_path = Path::new(safe_url.path());

        let (processed_files, new_files_map, success_count) = files_map_sync(
            self,
            current_files_map,
            location.as_ref(),
            processed_files,
            Some(dst_path),
            delete,
            false,
            true,
            follow_links,
        )
        .await?;

        self.update_files_container(
            success_count,
            current_version,
            new_files_map,
            processed_files,
            url,
            safe_url,
            update_nrs,
        )
        .await
    }

    /// # Add a file, either a local path or an already uploaded file, on an existing `FilesContainer`.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// # use sn_api::Safe;
    /// # let rt = tokio::runtime::Runtime::new().unwrap();
    /// # rt.block_on(async {
    /// #   let safe = Safe::connected(None, None, None, None).await.unwrap();
    ///     let (xorurl, _processed_files, _files_map) = safe.files_container_create_from("./testdata", None, true, true).await.unwrap();
    ///     let new_file_name = format!("{}/new_name_test.md", xorurl);
    ///     let (optional_version_map, new_processed_files) = safe.files_container_add("./testdata/test.md", &new_file_name, false, false, true).await.unwrap();
    ///     if let Some((version, new_files_map)) = optional_version_map {
    ///         println!("FilesContainer is now at version: {}", version);
    ///         println!("The local files that were synced up are: {:?}", new_processed_files);
    ///         println!("The FilesMap of the updated FilesContainer now is: {:?}", new_files_map);
    ///     }
    /// # });
    /// ```
    pub async fn files_container_add(
        &self,
        source_file: &str,
        url: &str,
        force: bool,
        update_nrs: bool,
        follow_links: bool,
    ) -> Result<(Option<(VersionHash, FilesMap)>, ProcessedFiles)> {
        debug!("Adding file to FilesContainer at {}", url);
        let (safe_url, current_version, current_files_map) =
            validate_files_add_params(self, source_file, url, update_nrs).await?;

        let dst_path = Path::new(safe_url.path());

        // Let's act according to if it's a local file path or a safe:// location
        let (processed_files, new_files_map, success_count) = if source_file.starts_with("safe://")
        {
            files_map_add_link(self, current_files_map, source_file, dst_path, force).await?
        } else {
            // We then assume source is a local path
            let source_path = Path::new(source_file);

            // Let's generate the list of local files paths, without uploading any new file yet.
            // Use dry runner only for this next operation
            let dry_runner = Safe::dry_runner(Some(self.xorurl_base));
            let processed_files = file_system_single_file(&dry_runner, source_path).await?;

            files_map_sync(
                self,
                current_files_map,
                source_path,
                processed_files,
                Some(dst_path),
                false,
                force,
                false,
                follow_links,
            )
            .await?
        };

        self.update_files_container(
            success_count,
            current_version,
            new_files_map,
            processed_files,
            url,
            safe_url,
            update_nrs,
        )
        .await
    }

    /// # Add a file, from raw bytes, on an existing `FilesContainer`.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// # use sn_api::Safe;
    /// # use bytes::Bytes;
    /// # let rt = tokio::runtime::Runtime::new().unwrap();
    /// # rt.block_on(async {
    /// #   let safe = Safe::connected(None, None, None, None).await.unwrap();
    ///     let (xorurl, _processed_files, _files_map) = safe.files_container_create_from("./testdata", None, true, true).await.unwrap();
    ///     let new_file_name = format!("{}/new_name_test.md", xorurl);
    ///     let (optional_version_map, new_processed_files) = safe.files_container_add_from_raw(Bytes::from("0123456789"), &new_file_name, false, false).await.unwrap();
    ///     if let Some((version, new_files_map)) = optional_version_map {
    ///         println!("FilesContainer is now at version: {}", version);
    ///         println!("The local files that were synced up are: {:?}", new_processed_files);
    ///         println!("The FilesMap of the updated FilesContainer now is: {:?}", new_files_map);
    ///     }
    /// # });
    /// ```
    pub async fn files_container_add_from_raw(
        &self,
        data: Bytes,
        url: &str,
        force: bool,
        update_nrs: bool,
    ) -> Result<(Option<(VersionHash, FilesMap)>, ProcessedFiles)> {
        let (safe_url, current_version, current_files_map) =
            validate_files_add_params(self, "", url, update_nrs).await?;

        let new_file_xorurl = self.store_bytes(data, None).await?;

        let dst_path = Path::new(safe_url.path());
        let (processed_files, new_files_map, success_count) =
            files_map_add_link(self, current_files_map, &new_file_xorurl, dst_path, force).await?;

        self.update_files_container(
            success_count,
            current_version,
            new_files_map,
            processed_files,
            url,
            safe_url,
            update_nrs,
        )
        .await
    }

    /// # Remove a file from an existing `FilesContainer`.
    ///
    /// ## Example
    ///
    /// ```no_run
    /// # use sn_api::Safe;
    /// # let rt = tokio::runtime::Runtime::new().unwrap();
    /// # rt.block_on(async {
    /// #   let safe = Safe::connected(None, None, None, None).await.unwrap();
    ///     let (xorurl, processed_files, files_map) = safe.files_container_create_from("./testdata/", None, true, true).await.unwrap();
    ///     let remote_file_path = format!("{}/test.md", xorurl);
    ///     let (version, new_processed_files, new_files_map) = safe.files_container_remove_path(&remote_file_path, false, false).await.unwrap();
    ///     println!("FilesContainer is now at version: {}", version);
    ///     println!("The files that were removed: {:?}", new_processed_files);
    ///     println!("The FilesMap of the updated FilesContainer now is: {:?}", new_files_map);
    /// # });
    /// ```
    pub async fn files_container_remove_path(
        &self,
        url: &str,
        recursive: bool,
        update_nrs: bool,
    ) -> Result<(VersionHash, ProcessedFiles, FilesMap)> {
        let safe_url = SafeUrl::from_url(url)?;
        let dst_path = safe_url.path();
        if dst_path.is_empty() {
            return Err(Error::InvalidInput(
                "The destination URL should include a target file path".to_string(),
            ));
        }

        // If NRS name shall be updated then the URL has to be an NRS-URL
        if update_nrs && safe_url.content_type() != ContentType::NrsMapContainer {
            return Err(Error::InvalidInput(
                "'update-nrs' is not allowed since the URL provided is not an NRS URL".to_string(),
            ));
        }

        let mut safe_url = self.parse_and_resolve_url(url).await?;

        // If the FilesContainer URL was resolved from an NRS name we need to remove
        // the version from it so we can fetch latest version of it
        safe_url.set_content_version(None);

        let (current_version, files_map) = match self.fetch_files_container(&safe_url).await? {
            Some(info) => info,
            None => {
                return Err(Error::EmptyContent(format!(
                    "FilesContainer found at \"{safe_url}\" was empty"
                )))
            }
        };

        let (processed_files, new_files_map, success_count) =
            files_map_remove_path(Path::new(dst_path), files_map, recursive)?;

        let version = if success_count == 0 {
            current_version
        } else {
            self.append_version_to_files_container(
                HashSet::from_iter([current_version]),
                &new_files_map,
                url,
                safe_url,
                update_nrs,
            )
            .await?
        };

        Ok((version, processed_files, new_files_map))
    }

    // Private helper to append new FilesMap entry to container, and/or return
    // information regarding the update and new version if so
    #[allow(clippy::too_many_arguments)]
    async fn update_files_container(
        &self,
        files_map_changes_count: u64,
        current_version: Option<VersionHash>,
        new_files_map: FilesMap,
        processed_files: ProcessedFiles,
        url: &str,
        safe_url: SafeUrl,
        update_nrs: bool,
    ) -> Result<(Option<(VersionHash, FilesMap)>, ProcessedFiles)> {
        if files_map_changes_count == 0 {
            if let Some(version) = current_version {
                // We had a FilesMap but there were no changes to it, so let's
                // return the existing version and files map, along with
                // details about the processed files.
                // Note: the 'new_files_map' should be the same as to 'current_files_map'.
                Ok((Some((version, new_files_map)), processed_files))
            } else {
                // The container was empty, and is still empty, but let's return
                // the details about proessed files still
                Ok((None, processed_files))
            }
        } else {
            // There were changes to current FilesMap, so append new version to the container
            let parent_versions = if let Some(version) = current_version {
                HashSet::from_iter([version])
            } else {
                HashSet::new()
            };

            let new_version = self
                .append_version_to_files_container(
                    parent_versions,
                    &new_files_map,
                    url,
                    safe_url,
                    update_nrs,
                )
                .await?;

            Ok((Some((new_version, new_files_map)), processed_files))
        }
    }

    // Private helper function to append new version of the FilesMap to the Files Container
    // It flagged with `update_nrs`, it will also update the link in the corresponding NRS Map Container
    #[allow(clippy::too_many_arguments)]
    async fn append_version_to_files_container(
        &self,
        current_version: HashSet<VersionHash>,
        new_files_map: &FilesMap,
        url: &str,
        mut safe_url: SafeUrl,
        update_nrs: bool,
    ) -> Result<VersionHash> {
        // The FilesContainer is updated by adding an entry containing the link to
        // the file with the serialised new version of the FilesMap.
        let files_map_xorurl = if !self.dry_run_mode {
            self.store_files_map(new_files_map).await?
        } else {
            "".to_string()
        };

        // append entry to register
        let entry = files_map_xorurl.as_bytes().to_vec();
        let replace = current_version.iter().map(|e| e.entry_hash()).collect();
        let entry_hash = &self
            .register_write(&safe_url.to_string(), entry, replace)
            .await?;
        let new_version: VersionHash = entry_hash.into();

        if update_nrs {
            // We need to update the link in the NRS container as well,
            // to link it to the new new_version of the FilesContainer we just generated
            safe_url.set_content_version(Some(new_version));
            let nrs_url = SafeUrl::from_url(url)?;
            let top_name = nrs_url.top_name();
            let _ = self.nrs_associate(top_name, &safe_url).await?;
        }

        Ok(new_version)
    }

    /// # Store a file
    ///
    /// Store files onto the network. The data will be saved as one or more chunks,
    /// depending on the size of the data. If it's less than 3072 bytes, it'll be stored in a single chunk,
    /// otherwise, it'll be stored in multiple chunks.
    ///
    /// ## Example
    /// ```no_run
    /// # use sn_api::Safe;
    /// # use bytes::Bytes;
    /// # let rt = tokio::runtime::Runtime::new().unwrap();
    /// # rt.block_on(async {
    /// #   let safe = Safe::connected(None, None, None, None).await.unwrap();
    ///     let data = Bytes::from("Something super good");
    ///     let xorurl = safe.store_bytes(data.clone(), Some("text/plain")).await.unwrap();
    ///     let received_data = safe.files_get(&xorurl, None).await.unwrap();
    ///     assert_eq!(received_data, data);
    /// # });
    /// ```
    pub async fn store_bytes(&self, bytes: Bytes, media_type: Option<&str>) -> Result<XorUrl> {
        let content_type = media_type.map_or_else(
            || Ok(ContentType::Raw),
            |media_type_str| {
                if SafeUrl::is_media_type_supported(media_type_str) {
                    Ok(ContentType::MediaType(media_type_str.to_string()))
                } else {
                    Err(Error::InvalidMediaType(format!(
                        "Media-type '{media_type_str}' not supported. You can pass 'None' as the 'media_type' for this content to be treated as raw",
                    )))
                }
            },
        )?;

        let address = if self.dry_run_mode {
            debug!(
                "Calculating network address for {} bytes of data",
                bytes.len()
            );
            Client::calculate_address(bytes)?
        } else {
            debug!("Storing {} bytes of data", bytes.len());
            let client = self.get_safe_client()?;
            client.upload_and_verify(bytes).await?
        };
        let xorurl = SafeUrl::from_bytes(address, content_type)?.encode(self.xorurl_base);

        Ok(xorurl)
    }

    /// # Get a file
    /// Get file from the network.
    ///
    /// ## Example
    /// ```no_run
    /// # use sn_api::Safe;
    /// # use bytes::Bytes;
    /// # let rt = tokio::runtime::Runtime::new().unwrap();
    /// # rt.block_on(async {
    /// #   let safe = Safe::connected(None, None, None, None).await.unwrap();
    ///     let data = Bytes::from("Something super good");
    ///     let xorurl = safe.store_bytes(data.clone(), None).await.unwrap();
    ///     let received_data = safe.files_get(&xorurl, None).await.unwrap();
    ///     assert_eq!(received_data, data);
    /// # });
    /// ```
    pub async fn files_get(&self, url: &str, range: Range) -> Result<Bytes> {
        // TODO: do we want ownership from other PKs yet?
        let safe_url = self.parse_and_resolve_url(url).await?;
        self.fetch_data(&safe_url, range).await
    }

    /// Fetch a file from a `SafeUrl` without performing any type of URL resolution
    pub(crate) async fn fetch_data(&self, safe_url: &SafeUrl, range: Range) -> Result<Bytes> {
        match safe_url.data_type() {
            DataType::File => self.get_bytes(safe_url.xorname(), range).await,
            other => Err(Error::ContentError(format!("{other}"))),
        }
    }

    async fn get_bytes(&self, address: XorName, range: Range) -> Result<Bytes> {
        debug!("Attempting to fetch data from {address:?}");
        let client = self.get_safe_client()?;
        let data = if let Some((start, end)) = range {
            let start = start.map(|start_index| start_index as usize).unwrap_or(0);
            let len = end
                .map(|end_index| end_index as usize - start)
                .unwrap_or(usize::MAX);

            client.read_from(address, start, len).await
        } else {
            client.read_bytes(address).await
        }
        .map_err(|err| Error::NetDataError(format!("Failed to GET file: {err:?}")))?;

        debug!(
            "{} bytes of data successfully retrieved from: {address:?}",
            data.len(),
        );

        Ok(data)
    }

    /// Fetch a file with the provided `SafeUrl`, without performing any type of URL resolution,
    /// from each of the data replicas on the network that match each of the indexes provided.
    pub(crate) async fn fetch_data_replicas(
        &self,
        safe_url: &SafeUrl,
        replicas_indexes: &[usize],
    ) -> Result<Vec<QueriedDataReplicas>> {
        match safe_url.data_type() {
            DataType::File => {
                let addr = safe_url.xorname();
                debug!("Attempting to fetch data from {addr:?}, with replicas indexes: {replicas_indexes:?}");
                let client = self.get_safe_client()?;
                client
                    .read_bytes_from_replicas(addr, replicas_indexes)
                    .await
                    .map_err(|err| {
                        Error::NetDataError(format!("Failed to GET file from replicas: {err:?}"))
                    })
            }
            other => Err(Error::ContentError(format!(
                "Cannot fetch a File from data replicas since the Url targets a {other}"
            ))),
        }
    }

    // Private helper to serialise a FilesMap and store it in a file
    async fn store_files_map(&self, files_map: &FilesMap) -> Result<String> {
        // The FilesMapContainer is a Register where each NRS Map version is
        // an entry containing the XOR-URL of the file that contains the serialised NrsMap.
        let serialised_files_map = serde_json::to_string(&files_map).map_err(|err| {
            Error::Serialisation(format!(
                "Couldn't serialise the FilesMap generated: {err:?}"
            ))
        })?;

        let files_map_xorurl = self
            .store_bytes(Bytes::from(serialised_files_map), None)
            .await?;

        Ok(files_map_xorurl)
    }
}

// Helper functions

// Make sure the input params are valid for a files_container_add operation
async fn validate_files_add_params(
    safe: &Safe,
    source_file: &str,
    url: &str,
    update_nrs: bool,
) -> Result<(SafeUrl, Option<VersionHash>, FilesMap)> {
    let safe_url = SafeUrl::from_url(url)?;

    // If NRS name shall be updated then the URL has to be an NRS-URL
    if update_nrs && safe_url.content_type() != ContentType::NrsMapContainer {
        return Err(Error::InvalidInput(
            "'update-nrs' is not allowed since the URL provided is not an NRS URL".to_string(),
        ));
    }

    let mut safe_url = safe.parse_and_resolve_url(url).await?;

    // If the FilesContainer URL was resolved from an NRS name we need to remove
    // the version from it so we can fetch latest version of it for sync-ing
    safe_url.set_content_version(None);

    // Let's act according to if it's a local file path or a safe:// location
    if source_file.starts_with("safe://") {
        let source_safe_url = SafeUrl::from_url(source_file)?;
        if source_safe_url.data_type() != DataType::File {
            return Err(Error::InvalidInput(format!(
                "The source URL should target a file ('{}'), but the URL provided targets a '{}'",
                DataType::File,
                source_safe_url.content_type()
            )));
        }

        if safe_url.path().is_empty() {
            return Err(Error::InvalidInput(
                "The destination URL should include a target file path since we are adding a link"
                    .to_string(),
            ));
        }
    }

    let (current_version, current_files_map) = match safe.fetch_files_container(&safe_url).await? {
        Some((version, files_map)) => (Some(version), files_map),
        None => (None, FilesMap::default()),
    };

    Ok((safe_url, current_version, current_files_map))
}

// From the location path and the destination path chosen by the user, calculate
// the destination path considering ending '/' in both the location and dst path
fn get_base_paths(location: &Path, dst_path: Option<&Path>) -> (String, String) {
    // Let's normalise the path to use '/' (instead of '\' as on Windows)
    let location_base_path = if location.to_str() == Some(".") {
        String::from("./")
    } else {
        normalise_path_separator(&location.display().to_string())
    };

    let new_dst_path = match dst_path {
        Some(path) => {
            let path_str = path.display().to_string();
            if path_str.is_empty() {
                "/".to_string()
            } else {
                path_str
            }
        }
        None => "/".to_string(),
    };

    // Let's first check if it ends with '/'
    let dst_base_path = if new_dst_path.ends_with('/') {
        if location_base_path.ends_with('/') {
            new_dst_path
        } else {
            // Location is a folder, then append it to dst path
            let parts_vec: Vec<&str> = location_base_path.split('/').collect();
            let dir_name = parts_vec[parts_vec.len() - 1];
            format!("{new_dst_path}{dir_name}")
        }
    } else {
        // Then just append an ending '/'
        format!("{new_dst_path}/")
    };

    (location_base_path, dst_base_path)
}

// From the provided list of local files paths, find the local changes made in comparison with the
// target FilesContainer, uploading new files as necessary, and creating a new FilesMap with file's
// metadata and their corresponding links, as well as generating the report of processed files
#[allow(clippy::too_many_arguments)]
async fn files_map_sync(
    safe: &Safe,
    mut current_files_map: FilesMap,
    location: &Path,
    new_content: ProcessedFiles,
    dst_path: Option<&Path>,
    delete: bool,
    force: bool,
    compare_file_content: bool,
    follow_links: bool,
) -> Result<(ProcessedFiles, FilesMap, u64)> {
    let (location_base_path, dst_base_path) = get_base_paths(location, dst_path);
    let mut updated_files_map = FilesMap::new();
    let mut processed_files = ProcessedFiles::new();
    let mut success_count = 0;

    for (local_file_name, _) in new_content.iter().filter(|(_, change)| change.is_success()) {
        let file_path = Path::new(&local_file_name);

        let file_name = RelativePath::new(
            &local_file_name
                .display()
                .to_string()
                .replace(&location_base_path, &dst_base_path),
        )
        .normalize();
        // Above normalize removes initial slash, and uses '\' if it's on Windows
        // here, we trim any trailing '/', as it could be a filename.
        let mut normalised_file_name = format!("/{}", normalise_path_separator(file_name.as_str()))
            .trim_end_matches('/')
            .to_string();

        if normalised_file_name.is_empty() {
            normalised_file_name = "/".to_string();
        }

        // Let's update FileInfo if there is a change or it doesn't exist in current_files_map
        match current_files_map.get(&normalised_file_name) {
            None => {
                // We need to add a new FileInfo
                if add_or_update_file_item(
                    safe,
                    local_file_name,
                    &normalised_file_name,
                    file_path,
                    &FileMeta::from_path(local_file_name, follow_links)?,
                    None, // no xorurl link
                    false,
                    &mut updated_files_map,
                    &mut processed_files,
                )
                .await
                {
                    success_count += 1;

                    // We remove self and any parent directories
                    // from the current list so we know it has been processed
                    let mut trail = Vec::<&str>::new();
                    for part in normalised_file_name.split('/') {
                        trail.push(part);
                        let ancestor = if trail.len() > 1 {
                            trail.join("/")
                        } else {
                            "/".to_string()
                        };
                        if ancestor != normalised_file_name {
                            if let Some(fi) = current_files_map.get(&ancestor) {
                                updated_files_map.insert(ancestor.clone(), fi.clone());
                                current_files_map.remove(&ancestor);
                            }
                        }
                    }
                }
            }
            Some(file_item) => {
                let is_modified =
                    is_file_item_modified(safe, Path::new(local_file_name), file_item).await;
                if force || (compare_file_content && is_modified) {
                    // We need to update the current FileInfo
                    if add_or_update_file_item(
                        safe,
                        local_file_name,
                        &normalised_file_name,
                        file_path,
                        &FileMeta::from_path(local_file_name.as_path(), follow_links)?,
                        None, // no xorurl link
                        true,
                        &mut updated_files_map,
                        &mut processed_files,
                    )
                    .await
                    {
                        success_count += 1;
                    }
                } else {
                    // No need to update FileInfo just copy the existing one
                    updated_files_map.insert(normalised_file_name.to_string(), file_item.clone());

                    if !force && !compare_file_content {
                        let (err_type, comp_str) = if is_modified {
                            (
                                Error::FileNameConflict(normalised_file_name.clone()),
                                "different",
                            )
                        } else {
                            (
                                Error::FileAlreadyExists(normalised_file_name.clone()),
                                "same",
                            )
                        };

                        processed_files.insert(
                            local_file_name.clone(),
                            FilesMapChange::Failed(format!("{err_type}")),
                        );
                        info!("Skipping file \"{}\" since a file named \"{}\" with {} content already exists on target. You can use the 'force' flag to replace the existing file with the new one", local_file_name.display(), normalised_file_name, comp_str);
                    }
                }

                // let's now remove it from the current list so we now it has been processed
                current_files_map.remove(&normalised_file_name);

                // We also remove any parent directories
                // from the current list, so they will not be deleted.
                let mut trail = Vec::<&str>::new();
                for part in normalised_file_name.split('/') {
                    trail.push(part);
                    let ancestor = if trail.len() > 1 {
                        trail.join("/")
                    } else {
                        "/".to_string()
                    };
                    if ancestor != normalised_file_name {
                        if let Some(fi) = current_files_map.get(&ancestor) {
                            updated_files_map.insert(ancestor.clone(), fi.clone());
                            current_files_map.remove(&ancestor);
                        }
                    }
                }
            }
        }
    }

    // Finally, unless 'delete' was set keep the files that are currently
    // in FilesContainer but not in source location
    for (file_name, file_item) in current_files_map.iter() {
        if !delete {
            updated_files_map.insert(file_name.to_string(), file_item.clone());
        } else {
            // note: files have link property, dirs and symlinks do not
            let xorurl = file_item
                .get(PREDICATE_LINK)
                .unwrap_or(&String::default())
                .to_string();

            processed_files.insert(PathBuf::from(file_name), FilesMapChange::Removed(xorurl));
            success_count += 1;
        }
    }

    Ok((processed_files, updated_files_map, success_count))
}

async fn is_file_item_modified(safe: &Safe, local_filename: &Path, file_item: &FileInfo) -> bool {
    if FileMeta::filetype_is_file(&file_item[PREDICATE_TYPE]) {
        // Use a dry runner only for this next operation
        let dry_runner = Safe::dry_runner(Some(safe.xorurl_base));

        match upload_file_to_net(&dry_runner, local_filename).await {
            Ok(local_xorurl) => file_item[PREDICATE_LINK] != local_xorurl,
            Err(_) => false,
        }
    } else {
        // for now, we just return false if a symlink or directory.
        // In the future, should check if symlink has been modified.
        // Also, could check if ctime or mtime is different, though that
        // could apply to files as well, and some use-cases would not want to
        // sync remotely if actual content has not changed.  So it should
        // probably be a user flag to enable.
        false
    }
}

async fn files_map_add_link(
    safe: &Safe,
    mut files_map: FilesMap,
    file_link: &str,
    file_name: &Path,
    force: bool,
) -> Result<(ProcessedFiles, FilesMap, u64)> {
    let mut processed_files = ProcessedFiles::new();
    let mut success_count = 0;
    let file_type = match SafeUrl::from_url(file_link) {
        Err(err) => {
            info!("Skipping file \"{}\". {}", file_link, err);
            processed_files.insert(
                PathBuf::from(file_link),
                FilesMapChange::Failed(format!("{err}")),
            );
            return Ok((processed_files, files_map, success_count));
        }
        Ok(safe_url) => match safe_url.content_type() {
            ContentType::MediaType(media_type) => media_type,
            other => format!("{other}"),
        },
    };

    let file_path = Path::new("");
    let file_size = ""; // unknown
    let file_name_str = file_name.display().to_string();

    // Let's update FileInfo if the link is different or it doesn't exist in the files_map
    let dry_runner = Safe::dry_runner(Some(safe.xorurl_base));
    match files_map.get(&file_name_str) {
        Some(current_file_item) => {
            let mut file_meta = FileMeta::from_file_item(current_file_item);
            file_meta.file_type = file_type;
            file_meta.file_size = file_size.to_string();

            let is_modified = if file_meta.is_file() {
                current_file_item[PREDICATE_LINK] != file_link
            } else {
                // directory: nothing to check.
                // symlink: TODO: check if sym-link path has changed.
                false
            };

            if is_modified {
                if force {
                    if add_or_update_file_item(
                        &dry_runner,
                        file_name,
                        &file_name_str,
                        file_path,
                        &file_meta,
                        Some(file_link),
                        true,
                        &mut files_map,
                        &mut processed_files,
                    )
                    .await
                    {
                        success_count += 1;
                    }
                } else {
                    info!("Skipping file \"{}\" since a file with name \"{}\" already exists on target. You can use the 'force' flag to replace the existing file with the new one", file_link, file_name_str);
                    processed_files.insert(
                        file_name.to_path_buf(),
                        FilesMapChange::Failed(format!(
                            "<{}>",
                            Error::FileNameConflict(file_name_str)
                        )),
                    );
                }
            } else {
                info!("Skipping file \"{}\" since a file with name \"{}\" already exists on target with the same link", file_link, file_name_str);
                processed_files.insert(
                    PathBuf::from(file_link),
                    FilesMapChange::Failed(format!(
                        "<{}>",
                        Error::FileAlreadyExists(file_name_str)
                    )),
                );
            }
        }
        None => {
            if add_or_update_file_item(
                &dry_runner,
                file_name,
                &file_name_str,
                file_path,
                &FileMeta::from_type_and_size(&file_type, file_size),
                Some(file_link),
                false,
                &mut files_map,
                &mut processed_files,
            )
            .await
            {
                success_count += 1;
            }
        }
    };

    Ok((processed_files, files_map, success_count))
}

// Remove a path from the FilesMap provided
fn files_map_remove_path(
    dst_path: &Path,
    mut files_map: FilesMap,
    recursive: bool,
) -> Result<(ProcessedFiles, FilesMap, u64)> {
    let mut processed_files = ProcessedFiles::default();
    let (success_count, new_files_map) = if recursive {
        let mut success_count = 0;
        let mut new_files_map = FilesMap::default();
        let folder_path = if !dst_path.ends_with("/") {
            format!("{}/", dst_path.display())
        } else {
            dst_path.display().to_string()
        };

        for (file_path, file_item) in files_map.iter() {
            // if the current file_path is a subfolder we remove it
            if file_path.starts_with(&folder_path) {
                // note: files have link property, dirs and symlinks do not
                let xorurl = file_item
                    .get(PREDICATE_LINK)
                    .unwrap_or(&String::default())
                    .to_string();

                processed_files.insert(PathBuf::from(file_path), FilesMapChange::Removed(xorurl));
                success_count += 1;
            } else {
                new_files_map.insert(file_path.to_string(), file_item.clone());
            }
        }
        (success_count, new_files_map)
    } else {
        let file_item = files_map
            .remove(&dst_path.display().to_string())
            .ok_or_else(|| Error::ContentError(format!(
                "No content found matching the \"{}\" path on the target FilesContainer. If you are trying to remove a folder rather than a file, you need to pass the 'recursive' flag",
                dst_path.display()
            )))?;

        // note: files have link property, dirs and symlinks do not
        let xorurl = file_item
            .get(PREDICATE_LINK)
            .unwrap_or(&String::default())
            .to_string();

        processed_files.insert(dst_path.to_path_buf(), FilesMapChange::Removed(xorurl));

        (1, files_map)
    };

    Ok((processed_files, new_files_map, success_count))
}

// From the provided list of local files paths and corresponding files XOR-URLs,
// create a FilesMap with file's metadata and their corresponding links
async fn files_map_create(
    safe: &Safe,
    content: &mut ProcessedFiles,
    location: &Path,
    dst_path: Option<&Path>,
    follow_links: bool,
) -> Result<FilesMap> {
    let mut files_map = FilesMap::default();

    let (location_base_path, dst_base_path) = get_base_paths(location, dst_path);

    // We want to iterate over the BTreeMap and also modify it.
    // We DON'T want to clone/dup the whole thing, might be very big.
    // Rust doesn't allow that exactly, but we can get the keys
    // to iterate over instead.  Cloning the keys isn't ideal
    // either, but is much less data.  Is there a more efficient way?
    let names = content.keys().cloned().collect::<Vec<_>>();
    for file_name in names {
        let link = match &content[&file_name] {
            FilesMapChange::Failed(_) => continue,
            FilesMapChange::Added(link)
            | FilesMapChange::Updated(link)
            | FilesMapChange::Removed(link) => link.clone(),
        };

        let new_file_name = RelativePath::new(
            &file_name
                .display()
                .to_string()
                .replace(&location_base_path, &dst_base_path),
        )
        .normalize();

        // Above normalize removes initial slash, and uses '\' if it's on Windows
        // here, we trim any trailing '/', as it could be a filename.
        let final_name = format!("/{}", normalise_path_separator(new_file_name.as_str()))
            .trim_end_matches('/')
            .to_string();

        debug!("FileInfo item name: {:?}", &file_name);

        add_or_update_file_item(
            safe,
            &file_name,
            &final_name,
            &file_name,
            &FileMeta::from_path(&file_name, follow_links)?,
            if link.is_empty() { None } else { Some(&link) },
            false,
            &mut files_map,
            content,
        )
        .await;
    }

    Ok(files_map)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{
        app::test_helpers::{new_safe_instance, random_nrs_name},
        register::EntryHash,
    };
    use anyhow::{anyhow, bail, Result};
    use assert_matches::assert_matches;
    use rand::{distributions::Alphanumeric, thread_rng, Rng};

    const TEST_DATA_FOLDER: &str = "./testdata/";
    const TEST_DATA_FOLDER_NO_SLASH: &str = "./testdata";

    // make some constants for these, in case entries in the testdata folder change.
    const TESTDATA_PUT_FILEITEM_COUNT: usize = 11;
    const TESTDATA_PUT_FILESMAP_COUNT: usize = 10; // TODO: review case of empty folder and empty file
    const TESTDATA_NO_SLASH_PUT_FILEITEM_COUNT: usize = 12;
    const TESTDATA_NO_SLASH_PUT_FILESMAP_COUNT: usize = 11; // TODO: review case of empty file
    const SUBFOLDER_PUT_FILEITEM_COUNT: usize = 2;
    const SUBFOLDER_NO_SLASH_PUT_FILEITEM_COUNT: usize = 3;

    // Helper function to create a files container with all files from TEST_DATA_FOLDER
    async fn new_files_container_from_testdata(
        safe: &Safe,
    ) -> Result<(String, ProcessedFiles, FilesMap)> {
        let (xorurl, processed_files, files_map) = safe
            .files_container_create_from(TEST_DATA_FOLDER, None, true, true)
            .await?;

        assert!(xorurl.starts_with("safe://"));
        assert_eq!(processed_files.len(), TESTDATA_PUT_FILEITEM_COUNT);
        assert_eq!(files_map.len(), TESTDATA_PUT_FILESMAP_COUNT);
        let _ = safe.fetch(&xorurl, None).await;

        Ok((xorurl, processed_files, files_map))
    }

    #[tokio::test]
    async fn test_files_map_create() -> Result<()> {
        let safe = new_safe_instance().await?;
        let mut processed_files = ProcessedFiles::new();
        let first_xorurl = SafeUrl::from_url("safe://top_xorurl")?.to_xorurl_string();
        let second_xorurl = SafeUrl::from_url("safe://second_xorurl")?.to_xorurl_string();

        processed_files.insert(
            PathBuf::from("./testdata/test.md"),
            FilesMapChange::Added(first_xorurl.clone()),
        );
        processed_files.insert(
            PathBuf::from("./testdata/subfolder/subexists.md"),
            FilesMapChange::Added(second_xorurl.clone()),
        );
        let files_map = files_map_create(
            &safe,
            &mut processed_files,
            Path::new(TEST_DATA_FOLDER_NO_SLASH),
            Some(Path::new("")),
            true,
        )
        .await?;
        assert_eq!(files_map.len(), 2);
        let file_item1 = &files_map["/testdata/test.md"];
        assert_eq!(file_item1[PREDICATE_LINK], first_xorurl);
        assert_eq!(file_item1[PREDICATE_TYPE], "text/markdown");
        assert_eq!(file_item1[PREDICATE_SIZE], "12");

        let file_item2 = &files_map["/testdata/subfolder/subexists.md"];
        assert_eq!(file_item2[PREDICATE_LINK], second_xorurl);
        assert_eq!(file_item2[PREDICATE_TYPE], "text/markdown");
        assert_eq!(file_item2[PREDICATE_SIZE], "23");
        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_create_empty() -> Result<()> {
        let safe = new_safe_instance().await?;
        let xorurl = safe.files_container_create().await?;

        assert!(xorurl.starts_with("safe://"));

        let _ = safe.fetch(&xorurl, None).await;

        // we check that the container is empty, i.e. no entry in the underlying Register.
        let file_map = safe.files_container_get(&xorurl).await?;
        assert!(file_map.is_none());

        // let's add a file
        let (content, new_processed_files) = safe
            .files_container_add("./testdata/test.md", &xorurl, false, false, false)
            .await?;
        let (_, new_files_map) =
            content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        assert_eq!(new_processed_files.len(), 1);
        assert_eq!(new_files_map.len(), 1);

        let filename = Path::new("./testdata/test.md");
        assert!(new_processed_files[filename].is_added());
        assert_eq!(
            new_processed_files[filename].link(),
            Some(&new_files_map["/test.md"][PREDICATE_LINK])
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_store_bytes() -> Result<()> {
        let safe = new_safe_instance().await?;
        let random_content: String = thread_rng()
            .sample_iter(&Alphanumeric)
            .take(20)
            .map(char::from)
            .collect();

        let file_xorurl = safe
            .store_bytes(Bytes::from(random_content.clone()), None)
            .await?;

        let retrieved = safe.files_get(&file_xorurl, None).await?;
        assert_eq!(retrieved, random_content.as_bytes());

        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_create_from_file() -> Result<()> {
        let safe = new_safe_instance().await?;
        let filename = Path::new("./testdata/test.md");
        let (xorurl, processed_files, files_map) = safe
            .files_container_create_from(&filename.display().to_string(), None, false, false)
            .await?;

        assert!(xorurl.starts_with("safe://"));
        assert_eq!(processed_files.len(), 1);
        assert_eq!(files_map.len(), 1);
        assert!(processed_files[filename].is_added());
        assert_eq!(
            processed_files[filename].link(),
            Some(&files_map["/test.md"][PREDICATE_LINK])
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_create_from_dry_run() -> Result<()> {
        let mut safe = new_safe_instance().await?;
        safe.dry_run_mode = true;
        let (xorurl, processed_files, files_map) = safe
            .files_container_create_from(TEST_DATA_FOLDER, None, true, false)
            .await?;

        assert!(xorurl.starts_with("safe://"));
        assert_eq!(processed_files.len(), TESTDATA_PUT_FILEITEM_COUNT);
        assert_eq!(files_map.len(), TESTDATA_PUT_FILESMAP_COUNT);

        let filename1 = Path::new("./testdata/test.md");
        assert!(processed_files[filename1].is_added());
        assert_matches!(processed_files[filename1].link(), Some(link) if !link.is_empty());
        assert_eq!(
            processed_files[filename1].link(),
            Some(&files_map["/test.md"][PREDICATE_LINK])
        );

        let filename2 = Path::new("./testdata/another.md");
        assert!(processed_files[filename2].is_added());
        assert_matches!(processed_files[filename2].link(), Some(link) if !link.is_empty());
        assert_eq!(
            processed_files[filename2].link(),
            Some(&files_map["/another.md"][PREDICATE_LINK])
        );

        let filename3 = Path::new("./testdata/subfolder/subexists.md");
        assert!(processed_files[filename3].is_added());
        assert_matches!(processed_files[filename3].link(), Some(link) if !link.is_empty());
        assert_eq!(
            processed_files[filename3].link(),
            Some(&files_map["/subfolder/subexists.md"][PREDICATE_LINK])
        );

        let filename4 = Path::new("./testdata/noextension");
        assert!(processed_files[filename4].is_added());
        assert_matches!(processed_files[filename4].link(), Some(link) if !link.is_empty());
        assert_eq!(
            processed_files[filename4].link(),
            Some(&files_map["/noextension"][PREDICATE_LINK])
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_create_from_folder_without_trailing_slash() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, processed_files, files_map) = safe
            .files_container_create_from(TEST_DATA_FOLDER_NO_SLASH, None, true, true)
            .await?;

        assert!(xorurl.starts_with("safe://"));
        assert_eq!(processed_files.len(), TESTDATA_NO_SLASH_PUT_FILEITEM_COUNT);
        assert_eq!(files_map.len(), TESTDATA_NO_SLASH_PUT_FILESMAP_COUNT);

        let filename1 = Path::new("./testdata/test.md");
        assert!(processed_files[filename1].is_added());
        assert_eq!(
            processed_files[filename1].link(),
            Some(&files_map["/testdata/test.md"][PREDICATE_LINK])
        );

        let filename2 = Path::new("./testdata/another.md");
        assert!(processed_files[filename2].is_added());
        assert_eq!(
            processed_files[filename2].link(),
            Some(&files_map["/testdata/another.md"][PREDICATE_LINK])
        );

        let filename3 = Path::new("./testdata/subfolder/subexists.md");
        assert!(processed_files[filename3].is_added());
        assert_eq!(
            processed_files[filename3].link(),
            Some(&files_map["/testdata/subfolder/subexists.md"][PREDICATE_LINK])
        );

        let filename4 = Path::new("./testdata/noextension");
        assert!(processed_files[filename4].is_added());
        assert_eq!(
            processed_files[filename4].link(),
            Some(&files_map["/testdata/noextension"][PREDICATE_LINK])
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_create_from_folder_with_trailing_slash() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (_, processed_files, files_map) = new_files_container_from_testdata(&safe).await?;

        let filename1 = Path::new("./testdata/test.md");
        assert!(processed_files[filename1].is_added());
        assert_eq!(
            processed_files[filename1].link(),
            Some(&files_map["/test.md"][PREDICATE_LINK])
        );

        let filename2 = Path::new("./testdata/another.md");
        assert!(processed_files[filename2].is_added());
        assert_eq!(
            processed_files[filename2].link(),
            Some(&files_map["/another.md"][PREDICATE_LINK])
        );

        let filename3 = Path::new("./testdata/subfolder/subexists.md");
        assert!(processed_files[filename3].is_added());
        assert_eq!(
            processed_files[filename3].link(),
            Some(&files_map["/subfolder/subexists.md"][PREDICATE_LINK])
        );

        let filename4 = Path::new("./testdata/noextension");
        assert!(processed_files[filename4].is_added());
        assert_eq!(
            processed_files[filename4].link(),
            Some(&files_map["/noextension"][PREDICATE_LINK])
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_create_from_dst_path_without_trailing_slash() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, processed_files, files_map) = safe
            .files_container_create_from(
                TEST_DATA_FOLDER_NO_SLASH,
                Some(Path::new("/myroot")),
                true,
                true,
            )
            .await?;

        assert!(xorurl.starts_with("safe://"));
        assert_eq!(processed_files.len(), TESTDATA_NO_SLASH_PUT_FILEITEM_COUNT);
        assert_eq!(files_map.len(), TESTDATA_NO_SLASH_PUT_FILESMAP_COUNT);

        let filename1 = Path::new("./testdata/test.md");
        assert!(processed_files[filename1].is_added());
        assert_eq!(
            processed_files[filename1].link(),
            Some(&files_map["/myroot/test.md"][PREDICATE_LINK])
        );

        let filename2 = Path::new("./testdata/another.md");
        assert!(processed_files[filename2].is_added());
        assert_eq!(
            processed_files[filename2].link(),
            Some(&files_map["/myroot/another.md"][PREDICATE_LINK])
        );

        let filename3 = Path::new("./testdata/subfolder/subexists.md");
        assert!(processed_files[filename3].is_added());
        assert_eq!(
            processed_files[filename3].link(),
            Some(&files_map["/myroot/subfolder/subexists.md"][PREDICATE_LINK])
        );

        let filename4 = Path::new("./testdata/noextension");
        assert!(processed_files[filename4].is_added());
        assert_eq!(
            processed_files[filename4].link(),
            Some(&files_map["/myroot/noextension"][PREDICATE_LINK])
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_create_from_dst_path_with_trailing_slash() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, processed_files, files_map) = safe
            .files_container_create_from(
                TEST_DATA_FOLDER_NO_SLASH,
                Some(Path::new("/myroot/")),
                true,
                true,
            )
            .await?;

        assert!(xorurl.starts_with("safe://"));
        assert_eq!(processed_files.len(), TESTDATA_NO_SLASH_PUT_FILEITEM_COUNT);
        assert_eq!(files_map.len(), TESTDATA_NO_SLASH_PUT_FILESMAP_COUNT);

        let filename1 = Path::new("./testdata/test.md");
        assert!(processed_files[filename1].is_added());
        assert_eq!(
            processed_files[filename1].link(),
            Some(&files_map["/myroot/testdata/test.md"][PREDICATE_LINK])
        );

        let filename2 = Path::new("./testdata/another.md");
        assert!(processed_files[filename2].is_added());
        assert_eq!(
            processed_files[filename2].link(),
            Some(&files_map["/myroot/testdata/another.md"][PREDICATE_LINK])
        );

        let filename3 = Path::new("./testdata/subfolder/subexists.md");
        assert!(processed_files[filename3].is_added());
        assert_eq!(
            processed_files[filename3].link(),
            Some(&files_map["/myroot/testdata/subfolder/subexists.md"][PREDICATE_LINK])
        );

        let filename4 = Path::new("./testdata/noextension");
        assert!(processed_files[filename4].is_added());
        assert_eq!(
            processed_files[filename4].link(),
            Some(&files_map["/myroot/testdata/noextension"][PREDICATE_LINK])
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_sync() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, processed_files, _) = new_files_container_from_testdata(&safe).await?;

        let (version0, _) = safe
            .files_container_get(&xorurl)
            .await?
            .ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        let (content, new_processed_files) = safe
            .files_container_sync("./testdata/subfolder/", &xorurl, true, true, false, false)
            .await?;
        let (version, new_files_map) =
            content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        assert_ne!(version, version0);
        assert_eq!(new_processed_files.len(), 2);
        assert_eq!(
            new_files_map.len(),
            TESTDATA_PUT_FILESMAP_COUNT + SUBFOLDER_PUT_FILEITEM_COUNT
        );

        let filename1 = Path::new("./testdata/test.md");
        assert!(processed_files[filename1].is_added());
        assert_eq!(
            processed_files[filename1].link(),
            Some(&new_files_map["/test.md"][PREDICATE_LINK])
        );

        let filename2 = Path::new("./testdata/another.md");
        assert!(processed_files[filename2].is_added());
        assert_eq!(
            processed_files[filename2].link(),
            Some(&new_files_map["/another.md"][PREDICATE_LINK])
        );

        let filename3 = Path::new("./testdata/subfolder/subexists.md");
        assert!(processed_files[filename3].is_added());
        assert_eq!(
            processed_files[filename3].link(),
            Some(&new_files_map["/subfolder/subexists.md"][PREDICATE_LINK])
        );

        let filename4 = Path::new("./testdata/noextension");
        assert!(processed_files[filename4].is_added());
        assert_eq!(
            processed_files[filename4].link(),
            Some(&new_files_map["/noextension"][PREDICATE_LINK])
        );

        let filename5 = Path::new("./testdata/subfolder/subexists.md");
        assert!(new_processed_files[filename5].is_added());
        assert_eq!(
            new_processed_files[filename5].link(),
            Some(&new_files_map["/subexists.md"][PREDICATE_LINK])
        );

        let filename6 = Path::new("./testdata/subfolder/sub2.md");
        assert!(new_processed_files[filename6].is_added());
        assert_eq!(
            new_processed_files[filename6].link(),
            Some(&new_files_map["/sub2.md"][PREDICATE_LINK])
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_sync_dry_run() -> Result<()> {
        let mut safe = new_safe_instance().await?;
        let (xorurl, processed_files, _) = new_files_container_from_testdata(&safe).await?;

        // set dry_run flag on
        safe.dry_run_mode = true;
        let (content, new_processed_files) = safe
            .files_container_sync("./testdata/subfolder/", &xorurl, true, true, false, false)
            .await?;
        let (_, new_files_map) =
            content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        assert_eq!(new_processed_files.len(), 2);
        assert_eq!(
            new_files_map.len(),
            TESTDATA_PUT_FILESMAP_COUNT + SUBFOLDER_PUT_FILEITEM_COUNT
        );

        let filename1 = Path::new("./testdata/test.md");
        assert!(processed_files[filename1].is_added());
        assert_eq!(
            processed_files[filename1].link(),
            Some(&new_files_map["/test.md"][PREDICATE_LINK])
        );

        let filename2 = Path::new("./testdata/another.md");
        assert!(processed_files[filename2].is_added());
        assert_eq!(
            processed_files[filename2].link(),
            Some(&new_files_map["/another.md"][PREDICATE_LINK])
        );

        let filename3 = Path::new("./testdata/subfolder/subexists.md");
        assert!(processed_files[filename3].is_added());
        assert_eq!(
            processed_files[filename3].link(),
            Some(&new_files_map["/subfolder/subexists.md"][PREDICATE_LINK])
        );

        let filename4 = Path::new("./testdata/noextension");
        assert!(processed_files[filename4].is_added());
        assert_eq!(
            processed_files[filename4].link(),
            Some(&new_files_map["/noextension"][PREDICATE_LINK])
        );

        let filename5 = Path::new("./testdata/subfolder/subexists.md");
        assert!(new_processed_files[filename5].is_added());
        assert_matches!(new_processed_files[filename5].link(), Some(link) if !link.is_empty());
        assert_eq!(
            new_processed_files[filename5].link(),
            Some(&new_files_map["/subexists.md"][PREDICATE_LINK])
        );

        let filename6 = Path::new("./testdata/subfolder/sub2.md");
        assert!(new_processed_files[filename6].is_added());
        assert_matches!(new_processed_files[filename6].link(), Some(link) if !link.is_empty());
        assert_eq!(
            new_processed_files[filename6].link(),
            Some(&new_files_map["/sub2.md"][PREDICATE_LINK])
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_sync_same_size() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, processed_files, files_map) = safe
            .files_container_create_from("./testdata/test.md", None, false, false)
            .await?;

        assert_eq!(processed_files.len(), 1);
        assert_eq!(files_map.len(), 1);

        let _ = safe.fetch(&xorurl, None).await;

        let (content, new_processed_files) = safe
            .files_container_sync(
                "./testdata/.subhidden/test.md",
                &xorurl,
                false,
                false,
                false,
                false,
            )
            .await?;
        let (_, new_files_map) =
            content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        assert_eq!(new_processed_files.len(), 1);
        assert_eq!(new_files_map.len(), 1);

        let filename1 = Path::new("./testdata/test.md");
        assert!(processed_files[filename1].is_added());
        assert_eq!(
            processed_files[filename1].link(),
            Some(&files_map["/test.md"][PREDICATE_LINK])
        );
        let filename2 = Path::new("./testdata/.subhidden/test.md");
        assert!(new_processed_files[filename2].is_updated());
        assert_eq!(
            new_processed_files[filename2].link(),
            Some(&new_files_map["/test.md"][PREDICATE_LINK])
        );

        // check sizes are the same but links are different
        assert_eq!(
            files_map["/test.md"][PREDICATE_SIZE],
            new_files_map["/test.md"][PREDICATE_SIZE]
        );
        assert_ne!(
            files_map["/test.md"][PREDICATE_LINK],
            new_files_map["/test.md"][PREDICATE_LINK]
        );

        Ok(())
    }

    #[tokio::test]
    #[ignore]
    async fn test_files_container_sync_with_versioned_target() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, _, _) = new_files_container_from_testdata(&safe).await?;

        match safe
            .files_container_sync(
                "./testdata/subfolder/",
                &xorurl,
                false,
                false,
                false,
                // FIXME: shall we just set this to false
                true, // this flag requests the update-nrs
            )
            .await
        {
            Ok(_) => Err(anyhow!("Sync was unexpectedly successful".to_string(),)),
            Err(Error::InvalidInput(msg)) => {
                assert_eq!(
                    msg,
                    format!("The target URL cannot contain a version: {xorurl}")
                );
                Ok(())
            }
            other => Err(anyhow!(
                "Error returned is not the expected one: {:?}",
                other
            )),
        }
    }

    #[tokio::test]
    async fn test_files_container_sync_with_delete() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, _, files_map) = new_files_container_from_testdata(&safe).await?;

        let _ = safe.fetch(&xorurl, None).await;
        let (version0, _) = safe
            .files_container_get(&xorurl)
            .await?
            .ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        let (version1_content, new_processed_files) = safe
            .files_container_sync(
                "./testdata/subfolder/",
                &xorurl,
                true,
                false,
                true, // this sets the delete flag
                false,
            )
            .await?;
        let (version1, new_files_map) =
            version1_content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        assert_ne!(version1, version0);
        assert_eq!(
            new_processed_files.len(),
            TESTDATA_PUT_FILESMAP_COUNT + SUBFOLDER_PUT_FILEITEM_COUNT
        );
        assert_eq!(new_files_map.len(), SUBFOLDER_PUT_FILEITEM_COUNT);

        // first check all previous files were removed
        let file_path1 = Path::new("/test.md");
        assert!(new_processed_files[file_path1].is_removed());
        assert_eq!(
            new_processed_files[file_path1].link(),
            Some(&files_map[&file_path1.display().to_string()][PREDICATE_LINK])
        );

        let file_path2 = Path::new("/another.md");
        assert!(new_processed_files[file_path2].is_removed());
        assert_eq!(
            new_processed_files[file_path2].link(),
            Some(&files_map[&file_path2.display().to_string()][PREDICATE_LINK])
        );

        let file_path3 = Path::new("/subfolder/subexists.md");
        assert!(new_processed_files[file_path3].is_removed());
        assert_eq!(
            new_processed_files[file_path3].link(),
            Some(&files_map[&file_path3.display().to_string()][PREDICATE_LINK])
        );

        let file_path4 = Path::new("/noextension");
        assert!(new_processed_files[file_path4].is_removed());
        assert_eq!(
            new_processed_files[file_path4].link(),
            Some(&files_map[&file_path4.display().to_string()][PREDICATE_LINK])
        );

        // and finally check the synced file was added
        let filename5 = Path::new("./testdata/subfolder/subexists.md");
        assert!(new_processed_files[filename5].is_added());
        assert_eq!(
            new_processed_files[filename5].link(),
            Some(&new_files_map["/subexists.md"][PREDICATE_LINK])
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_sync_delete_without_recursive() -> Result<()> {
        let safe = new_safe_instance().await?;
        match safe
            .files_container_sync(
                "./testdata/subfolder/",
                "some-url",
                false, // this sets the recursive flag to off
                false, // do not follow links
                true,  // this sets the delete flag
                false,
            )
            .await
        {
            Ok(_) => Err(anyhow!("Sync was unexpectedly successful".to_string(),)),
            Err(Error::InvalidInput(msg)) => {
                assert_eq!(
                    msg,
                    "'delete' is not allowed if 'recursive' is not set".to_string()
                );
                Ok(())
            }
            other => Err(anyhow!(
                "Error returned is not the expected one: {:?}",
                other
            )),
        }
    }

    #[tokio::test]
    async fn test_files_container_sync_update_nrs_unversioned_link() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, _, _) = new_files_container_from_testdata(&safe).await?;

        let nrsurl = random_nrs_name();
        let mut safe_url = SafeUrl::from_url(&xorurl)?;
        safe_url.set_content_version(None);
        let unversioned_link = safe_url;
        match safe.nrs_add(&nrsurl, &unversioned_link).await {
            Ok(_) => Err(anyhow!(
                "NRS create was unexpectedly successful".to_string(),
            )),
            Err(Error::UnversionedContentError(msg)) => {
                assert_eq!(
                msg,
                "FilesContainer content is versionable. NRS requires the supplied link to specify \
                a version hash.",
            );
                Ok(())
            }
            other => Err(anyhow!(
                "Error returned is not the expected one: {:?}",
                other
            )),
        }
    }

    #[tokio::test]
    async fn test_files_container_sync_update_nrs_with_xorurl() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, _, _) = new_files_container_from_testdata(&safe).await?;

        match safe
            .files_container_sync(
                "./testdata/subfolder/",
                &xorurl,
                false,
                false,
                false,
                true, // this flag requests the update-nrs
            )
            .await
        {
            Ok(_) => Err(anyhow!("Sync was unexpectedly successful".to_string(),)),
            Err(Error::InvalidInput(msg)) => {
                assert_eq!(
                    msg,
                    "'update-nrs' is not allowed since the URL provided is not an NRS URL"
                        .to_string()
                );
                Ok(())
            }
            other => Err(anyhow!(
                "Error returned is not the expected one: {:?}",
                other
            )),
        }
    }

    #[tokio::test]
    #[ignore] // TODO: tmp because hang
    async fn test_files_container_sync_update_nrs_versioned_link() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, _, _) = new_files_container_from_testdata(&safe).await?;

        let (version0, _) = safe
            .files_container_get(&xorurl)
            .await?
            .ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        let nrsurl = random_nrs_name();
        let mut safe_url = SafeUrl::from_url(&xorurl)?;
        safe_url.set_content_version(Some(version0));
        let (nrs_xorurl, did_create) = safe.nrs_add(&nrsurl, &safe_url).await?;
        assert!(did_create);
        let _ = safe.fetch(&nrs_xorurl.to_string(), None).await?;

        let (version1_content, _) = safe
            .files_container_sync(
                "./testdata/subfolder/",
                &nrsurl,
                false,
                false,
                false,
                true, // this flag requests the update-nrs
            )
            .await?;
        let (version1, _) =
            version1_content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        let mut safe_url = SafeUrl::from_url(&xorurl)?;
        safe_url.set_content_version(Some(version1));
        let new_link = safe.parse_and_resolve_url(&nrsurl).await?;
        // NRS points to the v0: check if different from v1 url
        assert_ne!(new_link.to_string(), safe_url.to_string());

        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_sync_target_path_without_trailing_slash() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, processed_files, _) = new_files_container_from_testdata(&safe).await?;

        let mut safe_url = SafeUrl::from_url(&xorurl)?;
        safe_url.set_path("path/when/sync");
        let (content, new_processed_files) = safe
            .files_container_sync(
                "./testdata/subfolder",
                &safe_url.to_string(),
                true,
                false,
                false,
                false,
            )
            .await?;
        let (_, new_files_map) =
            content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        assert_eq!(
            new_processed_files.len(),
            SUBFOLDER_NO_SLASH_PUT_FILEITEM_COUNT
        );
        assert_eq!(
            new_files_map.len(),
            TESTDATA_PUT_FILESMAP_COUNT + SUBFOLDER_NO_SLASH_PUT_FILEITEM_COUNT
        );

        let filename1 = Path::new("./testdata/test.md");
        assert!(processed_files[filename1].is_added());
        assert_eq!(
            processed_files[filename1].link(),
            Some(&new_files_map["/test.md"][PREDICATE_LINK])
        );

        let filename2 = Path::new("./testdata/another.md");
        assert!(processed_files[filename2].is_added());
        assert_eq!(
            processed_files[filename2].link(),
            Some(&new_files_map["/another.md"][PREDICATE_LINK])
        );

        let filename3 = Path::new("./testdata/subfolder/subexists.md");
        assert!(processed_files[filename3].is_added());
        assert_eq!(
            processed_files[filename3].link(),
            Some(&new_files_map["/subfolder/subexists.md"][PREDICATE_LINK])
        );

        let filename4 = Path::new("./testdata/noextension");
        assert!(processed_files[filename4].is_added());
        assert_eq!(
            processed_files[filename4].link(),
            Some(&new_files_map["/noextension"][PREDICATE_LINK])
        );

        // and finally check the synced file is there
        let filename5 = Path::new("./testdata/subfolder/subexists.md");
        assert!(new_processed_files[filename5].is_added());
        assert_eq!(
            new_processed_files[filename5].link(),
            Some(&new_files_map["/path/when/sync/subexists.md"][PREDICATE_LINK])
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_sync_target_path_with_trailing_slash() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, processed_files, _) = new_files_container_from_testdata(&safe).await?;

        let mut safe_url = SafeUrl::from_url(&xorurl)?;
        safe_url.set_path("/path/when/sync/");
        let (content, new_processed_files) = safe
            .files_container_sync(
                "./testdata/subfolder",
                &safe_url.to_string(),
                true,
                false,
                false,
                false,
            )
            .await?;
        let (_, new_files_map) =
            content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        assert_eq!(
            new_processed_files.len(),
            SUBFOLDER_NO_SLASH_PUT_FILEITEM_COUNT
        );
        assert_eq!(
            new_files_map.len(),
            TESTDATA_PUT_FILESMAP_COUNT + SUBFOLDER_NO_SLASH_PUT_FILEITEM_COUNT
        );

        let filename1 = Path::new("./testdata/test.md");
        assert!(processed_files[filename1].is_added());
        assert_eq!(
            processed_files[filename1].link(),
            Some(&new_files_map["/test.md"][PREDICATE_LINK])
        );

        let filename2 = Path::new("./testdata/another.md");
        assert!(processed_files[filename2].is_added());
        assert_eq!(
            processed_files[filename2].link(),
            Some(&new_files_map["/another.md"][PREDICATE_LINK])
        );

        let filename3 = Path::new("./testdata/subfolder/subexists.md");
        assert!(processed_files[filename3].is_added());
        assert_eq!(
            processed_files[filename3].link(),
            Some(&new_files_map["/subfolder/subexists.md"][PREDICATE_LINK])
        );

        let filename4 = Path::new("./testdata/noextension");
        assert!(processed_files[filename4].is_added());
        assert_eq!(
            processed_files[filename4].link(),
            Some(&new_files_map["/noextension"][PREDICATE_LINK])
        );

        // and finally check the synced file is there
        let filename5 = Path::new("./testdata/subfolder/subexists.md");
        assert!(new_processed_files[filename5].is_added());
        assert_eq!(
            new_processed_files[filename5].link(),
            Some(&new_files_map["/path/when/sync/subfolder/subexists.md"][PREDICATE_LINK])
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_get() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, _, files_map) = new_files_container_from_testdata(&safe).await?;

        let (_, fetched_files_map) = safe
            .files_container_get(&xorurl)
            .await?
            .ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        assert_eq!(fetched_files_map.len(), TESTDATA_PUT_FILESMAP_COUNT);
        assert_eq!(files_map.len(), fetched_files_map.len());
        assert_eq!(files_map["/test.md"], fetched_files_map["/test.md"]);
        assert_eq!(files_map["/another.md"], fetched_files_map["/another.md"]);
        assert_eq!(
            files_map["/subfolder/subexists.md"],
            fetched_files_map["/subfolder/subexists.md"]
        );
        assert_eq!(files_map["/noextension"], fetched_files_map["/noextension"]);

        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_version() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, _, _) = new_files_container_from_testdata(&safe).await?;

        let (version0, _) = safe
            .files_container_get(&xorurl)
            .await?
            .ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        let (version1_content, _) = safe
            .files_container_sync(
                "./testdata/subfolder/",
                &xorurl,
                true,
                false,
                true, // this sets the delete flag,
                false,
            )
            .await?;
        let (version1, _) =
            version1_content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        assert_ne!(version1, version0);

        let mut safe_url = SafeUrl::from_url(&xorurl)?;
        safe_url.set_content_version(None);
        let (version, _) = safe
            .files_container_get(&safe_url.to_string())
            .await?
            .ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;
        assert_eq!(version, version1);

        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_get_with_version() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, _, files_map) = new_files_container_from_testdata(&safe).await?;

        let (version0, _) = safe
            .files_container_get(&xorurl)
            .await?
            .ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        // let's create a new version of the files container
        let (version1_content, _) = safe
            .files_container_sync(
                "./testdata/subfolder/",
                &xorurl,
                true,
                false,
                true, // this sets the delete flag
                false,
            )
            .await?;
        let (version1, new_files_map) =
            version1_content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        // let's fetch version 0
        let mut safe_url = SafeUrl::from_url(&xorurl)?;
        safe_url.set_content_version(Some(version0));
        let (version, v0_files_map) = safe
            .files_container_get(&safe_url.to_string())
            .await?
            .ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        assert_eq!(version, version0);
        assert_eq!(files_map, v0_files_map);
        // let's check that one of the files in v1 is still there
        let file_path1 = Path::new("/test.md");
        assert_eq!(
            files_map[&file_path1.display().to_string()][PREDICATE_LINK],
            v0_files_map[&file_path1.display().to_string()][PREDICATE_LINK]
        );

        // let's fetch version1
        safe_url.set_content_version(Some(version1));
        let (version, v1_files_map) = safe
            .files_container_get(&safe_url.to_string())
            .await?
            .ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        assert_eq!(version, version1);
        assert_eq!(new_files_map, v1_files_map);
        // let's check that some of the files are no in v2 anymore
        let file_path2 = Path::new("/another.md");
        let file_path3 = Path::new("/subfolder/subexists.md");
        let file_path4 = Path::new("/noextension");
        assert!(v1_files_map
            .get(&file_path1.display().to_string())
            .is_none());
        assert!(v1_files_map
            .get(&file_path2.display().to_string())
            .is_none());
        assert!(v1_files_map
            .get(&file_path3.display().to_string())
            .is_none());
        assert!(v1_files_map
            .get(&file_path4.display().to_string())
            .is_none());

        // let's fetch invalid version
        let random_hash = EntryHash(rand::thread_rng().gen::<[u8; 32]>());
        let version_hash = VersionHash::from(&random_hash);
        safe_url.set_content_version(Some(version_hash));
        match safe.files_container_get(&safe_url.to_string()).await {
            Ok(_) => Err(anyhow!(
                "Unexpectedly retrieved invalid version of container".to_string(),
            )),
            Err(Error::VersionNotFound(msg)) => {
                assert_eq!(
                    msg,
                    format!("Version '{version_hash}' is invalid for FilesContainer found at \"{safe_url}\"")
                );
                Ok(())
            }
            other => Err(anyhow!(
                "Error returned is not the expected one: {:?}",
                other
            )),
        }
    }

    #[tokio::test]
    async fn test_files_container_create_from_get_empty_folder() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, _, files_map) = new_files_container_from_testdata(&safe).await?;

        let (_, files_map_get) = safe
            .files_container_get(&xorurl.to_string())
            .await?
            .ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        assert_eq!(files_map, files_map_get);
        assert_eq!(files_map_get["/emptyfolder"], files_map["/emptyfolder"]);
        assert_eq!(
            files_map_get["/emptyfolder"]["type"],
            MIMETYPE_FILESYSTEM_DIR
        );

        Ok(())
    }

    #[tokio::test]
    #[ignore = "fix unknown issue"]
    async fn test_files_container_sync_with_nrs_url() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, _, _) = safe
            .files_container_create_from("./testdata/test.md", None, false, true)
            .await?;
        let _ = safe.fetch(&xorurl, None).await;
        let (version0, _) = safe
            .files_container_get(&xorurl)
            .await?
            .ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        let nrsurl = random_nrs_name();
        let mut safe_url = SafeUrl::from_url(&xorurl)?;
        safe_url.set_content_version(Some(version0));
        let (nrs_xorurl, did_create) = safe.nrs_add(&nrsurl, &safe_url).await?;

        assert!(did_create);
        let _ = safe.fetch(&nrs_xorurl.to_string(), None).await?;

        let _ = safe
            .files_container_sync("./testdata/subfolder/", &xorurl, false, false, false, false)
            .await?;

        let (version2_content, _) = safe
            .files_container_sync(
                TEST_DATA_FOLDER,
                &nrsurl,
                false,
                false,
                false,
                true, // this flag requests the update-nrs
            )
            .await?;
        let (version2, _) =
            version2_content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        // now it should look like:
        // safe://<nrs>
        // ├── .hidden.txt
        // ├── another.md
        // ├── noextension
        // ├── sub2.md
        // ├── subexists.md
        // └── test.md
        //
        // So, we have 6 items.
        let (version, fetched_files_map) = safe
            .files_container_get(&xorurl)
            .await?
            .ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;
        assert_eq!(version, version2);
        assert_eq!(fetched_files_map.len(), 6);

        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_add() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, processed_files, files_map) = safe
            .files_container_create_from("./testdata/subfolder/", None, false, true)
            .await?;
        assert_eq!(processed_files.len(), SUBFOLDER_PUT_FILEITEM_COUNT);
        assert_eq!(files_map.len(), SUBFOLDER_PUT_FILEITEM_COUNT);
        let _ = safe.fetch(&xorurl, None).await;
        let (version0, _) = safe
            .files_container_get(&xorurl)
            .await?
            .ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        let mut url_with_path = SafeUrl::from_xorurl(&xorurl)?;
        url_with_path.set_path("/new_filename_test.md");

        let (version1_content, new_processed_files) = safe
            .files_container_add(
                "./testdata/test.md",
                &url_with_path.to_string(),
                false,
                false,
                false,
            )
            .await?;
        let (version1, new_files_map) =
            version1_content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        assert_ne!(version1, version0);
        assert_eq!(new_processed_files.len(), 1);
        assert_eq!(new_files_map.len(), SUBFOLDER_PUT_FILEITEM_COUNT + 1);

        let filename1 = Path::new("./testdata/subfolder/subexists.md");
        assert!(processed_files[filename1].is_added());
        assert_eq!(
            processed_files[filename1].link(),
            Some(&new_files_map["/subexists.md"][PREDICATE_LINK])
        );

        let filename2 = Path::new("./testdata/subfolder/sub2.md");
        assert!(processed_files[filename2].is_added());
        assert_eq!(
            processed_files[filename2].link(),
            Some(&new_files_map["/sub2.md"][PREDICATE_LINK])
        );

        let filename3 = Path::new("./testdata/test.md");
        assert!(new_processed_files[filename3].is_added());
        assert_eq!(
            new_processed_files[filename3].link(),
            Some(&new_files_map["/new_filename_test.md"][PREDICATE_LINK])
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_add_dry_run() -> Result<()> {
        let mut safe = new_safe_instance().await?;
        let (xorurl, processed_files, files_map) = safe
            .files_container_create_from("./testdata/subfolder/", None, false, true)
            .await?;
        assert_eq!(processed_files.len(), SUBFOLDER_PUT_FILEITEM_COUNT);
        assert_eq!(files_map.len(), SUBFOLDER_PUT_FILEITEM_COUNT);
        let _ = safe.fetch(&xorurl, None).await;

        let mut url_with_path = SafeUrl::from_xorurl(&xorurl)?;
        url_with_path.set_path("/new_filename_test.md");

        safe.dry_run_mode = true;
        let (version1_content, new_processed_files) = safe
            .files_container_add(
                "./testdata/test.md",
                &url_with_path.to_string(),
                false,
                false,
                false,
            )
            .await?;
        let (_, new_files_map) =
            version1_content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        // skip version hash check since not NotImplemented
        assert_eq!(new_processed_files.len(), 1);
        assert_eq!(new_files_map.len(), SUBFOLDER_PUT_FILEITEM_COUNT + 1);

        // a dry run again should give the exact same results
        let (version2_content, new_processed_files2) = safe
            .files_container_add(
                "./testdata/test.md",
                &url_with_path.to_string(),
                false,
                false,
                false,
            )
            .await?;
        let (_, new_files_map2) =
            version2_content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        assert_eq!(new_processed_files.len(), new_processed_files2.len());
        assert_eq!(new_files_map.len(), new_files_map2.len());

        let filename = Path::new("./testdata/test.md");
        assert!(new_processed_files[filename].is_added());
        assert!(new_processed_files2[filename].is_added());
        assert_eq!(
            new_processed_files[filename].link(),
            Some(&new_files_map["/new_filename_test.md"][PREDICATE_LINK])
        );
        assert_eq!(
            new_processed_files2[filename].link(),
            Some(&new_files_map2["/new_filename_test.md"][PREDICATE_LINK])
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_add_dir() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, processed_files, files_map) = safe
            .files_container_create_from("./testdata/subfolder/", None, false, true)
            .await?;
        assert_eq!(processed_files.len(), SUBFOLDER_PUT_FILEITEM_COUNT); // root "/" + 2 files
        assert_eq!(files_map.len(), SUBFOLDER_PUT_FILEITEM_COUNT);
        let _ = safe.fetch(&xorurl, None).await;

        match safe
            .files_container_add(TEST_DATA_FOLDER_NO_SLASH, &xorurl, false, false, false)
            .await
        {
            Ok(_) => Err(anyhow!(
                "Unexpectedly added a folder to files container".to_string(),
            )),
            Err(Error::InvalidInput(msg)) => {
                assert_eq!(
                    msg,
                    "'./testdata' is a directory, only individual files can be added. Use files sync operation for uploading folders".to_string(),
                );
                Ok(())
            }
            other => Err(anyhow!(
                "Error returned is not the expected one: {:?}",
                other
            )),
        }
    }

    #[tokio::test]
    async fn test_files_container_add_existing_name() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, processed_files, files_map) = safe
            .files_container_create_from("./testdata/subfolder/", None, false, true)
            .await?;
        assert_eq!(processed_files.len(), SUBFOLDER_PUT_FILEITEM_COUNT);
        assert_eq!(files_map.len(), SUBFOLDER_PUT_FILEITEM_COUNT);

        let _ = safe.fetch(&xorurl, None).await;
        let (version0, _) = safe
            .files_container_get(&xorurl)
            .await?
            .ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        let mut url_with_path = SafeUrl::from_xorurl(&xorurl)?;
        url_with_path.set_path("/sub2.md");

        // let's try to add a file with same target name and same content, it should fail
        let filename1 = Path::new("./testdata/subfolder/sub2.md");
        let (version1_content, new_processed_files) = safe
            .files_container_add(
                &filename1.display().to_string(),
                &url_with_path.to_string(),
                false,
                false,
                false,
            )
            .await?;
        let (version1, new_files_map) =
            version1_content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        assert_eq!(version1, version0);
        assert_eq!(new_processed_files.len(), 1);
        assert_eq!(new_files_map.len(), SUBFOLDER_PUT_FILEITEM_COUNT);
        assert_matches!(
            &new_processed_files[filename1],
            FilesMapChange::Failed(msg) if msg == &format!("{}", Error::FileAlreadyExists("/sub2.md".to_string()))
        );
        assert_eq!(files_map, new_files_map);

        // let's try to add a file with same target name but with different content, it should still fail
        let filename2 = Path::new("./testdata/test.md");
        let (version2_content, new_processed_files) = safe
            .files_container_add(
                &filename2.display().to_string(),
                &url_with_path.to_string(),
                false,
                false,
                false,
            )
            .await?;
        let (version2, new_files_map) =
            version2_content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        assert_eq!(version2, version0);
        assert_eq!(new_processed_files.len(), 1);
        assert_eq!(new_files_map.len(), SUBFOLDER_PUT_FILEITEM_COUNT);
        assert_matches!(
            &new_processed_files[filename2],
            FilesMapChange::Failed(msg) if msg == &format!("{}", Error::FileNameConflict("/sub2.md".to_string()))
        );
        assert_eq!(files_map, new_files_map);

        // let's now force it
        let (version3_content, new_processed_files) = safe
            .files_container_add(
                &filename2.display().to_string(),
                &url_with_path.to_string(),
                true, //force it
                false,
                false,
            )
            .await?;
        let (version3, new_files_map) =
            version3_content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        assert_ne!(version3, version0);
        assert_eq!(new_processed_files.len(), 1);
        assert_eq!(new_files_map.len(), SUBFOLDER_PUT_FILEITEM_COUNT);
        assert!(new_processed_files[filename2].is_updated());
        assert_eq!(
            new_processed_files[filename2].link(),
            Some(&new_files_map["/sub2.md"]["link"])
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_fail_add_or_sync_invalid_path() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, processed_files, files_map) = safe
            .files_container_create_from("./testdata/test.md", None, false, true)
            .await?;
        assert_eq!(processed_files.len(), 1);
        assert_eq!(files_map.len(), 1);
        let _ = safe.fetch(&xorurl, None).await;

        match safe
            .files_container_sync("/non-existing-path", &xorurl, false, false, false, false)
            .await
        {
            Ok(_) => {
                bail!("Unexpectedly added a folder to files container".to_string(),)
            }
            Err(Error::FileSystemError(msg)) => {
                assert!(msg
                    .starts_with("Couldn't read metadata from source path ('/non-existing-path')"))
            }
            other => {
                bail!("Error returned is not the expected one: {:?}", other)
            }
        }

        let mut url_with_path = SafeUrl::from_xorurl(&xorurl)?;
        url_with_path.set_path("/test.md");

        match safe
            .files_container_add(
                "/non-existing-path",
                &url_with_path.to_string(),
                false,
                false,
                false,
            )
            .await
        {
            Ok(_) => Err(anyhow!(
                "Unexpectedly added a folder to files container".to_string(),
            )),
            Err(Error::FileSystemError(msg)) => {
                assert!(msg
                    .starts_with("Couldn't read metadata from source path ('/non-existing-path')"));
                Ok(())
            }
            other => Err(anyhow!(
                "Error returned is not the expected one: {:?}",
                other
            )),
        }
    }

    #[tokio::test]
    async fn test_files_container_add_a_url() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, processed_files, files_map) = safe
            .files_container_create_from("./testdata/subfolder/", None, false, true)
            .await?;
        assert_eq!(processed_files.len(), SUBFOLDER_PUT_FILEITEM_COUNT);
        assert_eq!(files_map.len(), SUBFOLDER_PUT_FILEITEM_COUNT);
        let _ = safe.fetch(&xorurl, None).await;
        let (version0, _) = safe
            .files_container_get(&xorurl)
            .await?
            .ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        let data = Bytes::from("0123456789");
        let file_xorurl = safe.store_bytes(data.clone(), None).await?;
        let new_filename = Path::new("/new_filename_test.md");

        let mut url_with_path = SafeUrl::from_xorurl(&xorurl)?;
        url_with_path.set_path(&new_filename.display().to_string());

        let (version1_content, new_processed_files) = safe
            .files_container_add(
                &file_xorurl,
                &url_with_path.to_string(),
                false,
                false,
                false,
            )
            .await?;
        let (version1, new_files_map) =
            version1_content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        assert_ne!(version1, version0);
        assert_eq!(new_processed_files.len(), 1);
        assert_eq!(new_files_map.len(), SUBFOLDER_PUT_FILEITEM_COUNT + 1);

        let filename1 = Path::new("./testdata/subfolder/subexists.md");
        assert!(processed_files[filename1].is_added());
        assert_eq!(
            processed_files[filename1].link(),
            Some(&new_files_map["/subexists.md"][PREDICATE_LINK])
        );

        let filename2 = Path::new("./testdata/subfolder/sub2.md");
        assert!(processed_files[filename2].is_added());
        assert_eq!(
            processed_files[filename2].link(),
            Some(&new_files_map["/sub2.md"][PREDICATE_LINK])
        );

        assert!(new_processed_files[new_filename].is_added());
        assert_eq!(
            new_processed_files[new_filename].link(),
            Some(&new_files_map[&new_filename.display().to_string()][PREDICATE_LINK])
        );
        assert_eq!(
            new_files_map[&new_filename.display().to_string()][PREDICATE_LINK],
            file_xorurl
        );

        // let's add another file but with the same name
        let data = Bytes::from("9876543210");
        let other_file_xorurl = safe.store_bytes(data.clone(), None).await?;
        let (version2_content, mut new_processed_files) = safe
            .files_container_add(
                &other_file_xorurl,
                &url_with_path.to_string(),
                true, // force to overwrite it with new link
                false,
                false,
            )
            .await?;
        let (mut version2, mut new_files_map) =
            version2_content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        // we know there a change, so we wait for an udpated version here
        while version2 == version1 {
            let (version2_content, new_new_processed_files) = safe
                .files_container_add(
                    &other_file_xorurl,
                    &url_with_path.to_string(),
                    true, // force to overwrite it with new link
                    false,
                    false,
                )
                .await?;

            let (new_version2, new_new_files_map) = version2_content
                .ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;
            version2 = new_version2;
            new_files_map = new_new_files_map;
            new_processed_files = new_new_processed_files;
        }

        assert_ne!(version2, version0);
        assert_ne!(version2, version1);
        assert_eq!(new_processed_files.len(), 1);
        assert_eq!(new_files_map.len(), SUBFOLDER_PUT_FILEITEM_COUNT + 1);
        assert!(new_processed_files[new_filename].is_updated());
        assert_eq!(
            new_processed_files[new_filename].link(),
            Some(&new_files_map[&new_filename.display().to_string()][PREDICATE_LINK])
        );
        assert_eq!(
            new_files_map[&new_filename.display().to_string()][PREDICATE_LINK],
            other_file_xorurl
        );

        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_add_from_raw() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, processed_files, files_map) = safe
            .files_container_create_from("./testdata/subfolder/", None, false, true)
            .await?;
        assert_eq!(processed_files.len(), SUBFOLDER_PUT_FILEITEM_COUNT);
        assert_eq!(files_map.len(), SUBFOLDER_PUT_FILEITEM_COUNT);
        let _ = safe.fetch(&xorurl, None).await;
        let (version0, _) = safe
            .files_container_get(&xorurl)
            .await?
            .ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        let data = Bytes::from("0123456789");
        let new_filename = Path::new("/new_filename_test.md");

        let mut url_with_path = SafeUrl::from_xorurl(&xorurl)?;
        url_with_path.set_path(&new_filename.display().to_string());

        let (version1_content, new_processed_files) = safe
            .files_container_add_from_raw(data.clone(), &url_with_path.to_string(), false, false)
            .await?;
        let (version1, new_files_map) =
            version1_content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        assert_ne!(version1, version0);
        assert_eq!(new_processed_files.len(), 1);
        assert_eq!(new_files_map.len(), SUBFOLDER_PUT_FILEITEM_COUNT + 1);

        assert!(new_processed_files[new_filename].is_added());
        assert_eq!(
            new_processed_files[new_filename].link(),
            Some(&new_files_map[&new_filename.display().to_string()][PREDICATE_LINK])
        );

        // let's add another file but with the same name
        let data = Bytes::from("9876543210");
        let (version2_content, new_processed_files) = safe
            .files_container_add_from_raw(
                data.clone(),
                &url_with_path.to_string(),
                true, // force to overwrite it with new link
                false,
            )
            .await?;
        let (version2, new_files_map) =
            version2_content.ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        assert_ne!(version2, version0);
        assert_ne!(version2, version1);
        assert_eq!(new_processed_files.len(), 1);
        assert_eq!(new_files_map.len(), SUBFOLDER_PUT_FILEITEM_COUNT + 1);
        assert!(new_processed_files[new_filename].is_updated());
        assert_eq!(
            new_processed_files[new_filename].link(),
            Some(&new_files_map[&new_filename.display().to_string()][PREDICATE_LINK])
        );
        Ok(())
    }

    #[tokio::test]
    async fn test_files_container_remove_path() -> Result<()> {
        let safe = new_safe_instance().await?;
        let (xorurl, _, files_map) = new_files_container_from_testdata(&safe).await?;

        let (version0, _) = safe
            .files_container_get(&xorurl)
            .await?
            .ok_or_else(|| anyhow!("files container was unexpectedly empty"))?;

        let mut url_with_path = SafeUrl::from_xorurl(&xorurl)?;
        url_with_path.set_path("/test.md");

        // let's remove a file first
        let (version1, new_processed_files, new_files_map) = safe
            .files_container_remove_path(&url_with_path.to_string(), false, false)
            .await?;

        assert_ne!(version1, version0);
        assert_eq!(new_processed_files.len(), 1);
        assert_eq!(new_files_map.len(), TESTDATA_PUT_FILESMAP_COUNT - 1);

        let filepath = Path::new("/test.md");
        assert!(new_processed_files[filepath].is_removed());
        assert_eq!(
            new_processed_files[filepath].link(),
            Some(&files_map[&filepath.display().to_string()][PREDICATE_LINK])
        );

        // let's remove an entire folder now with recursive flag
        url_with_path.set_path("/subfolder");
        let (version2, new_processed_files, new_files_map) = safe
            .files_container_remove_path(&url_with_path.to_string(), true, false)
            .await?;

        assert_ne!(version2, version0);
        assert_ne!(version2, version1);
        assert_eq!(new_processed_files.len(), 2);
        assert_eq!(
            new_files_map.len(),
            TESTDATA_PUT_FILESMAP_COUNT - SUBFOLDER_PUT_FILEITEM_COUNT - 1
        );

        let filename1 = Path::new("/subfolder/subexists.md");
        assert!(new_processed_files[filename1].is_removed());
        assert_eq!(
            new_processed_files[filename1].link(),
            Some(&files_map[&filename1.display().to_string()][PREDICATE_LINK])
        );

        let filename2 = Path::new("/subfolder/sub2.md");
        assert!(new_processed_files[filename2].is_removed());
        assert_eq!(
            new_processed_files[filename2].link(),
            Some(&files_map[&filename2.display().to_string()][PREDICATE_LINK])
        );

        Ok(())
    }
}