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
use std::{collections::HashMap, str::FromStr};

use crate::{
    resp::{
        cmd, BulkString, CommandArgs, FromKeyValueValueArray, FromSingleValueArray, FromValue,
        HashMapExt, IntoArgs, KeyValueArgOrCollection, SingleArgOrCollection, Value,
    },
    CommandResult, Error, Future, MonitorStream, PrepareCommand, Result,
};

/// A group of Redis commands related to Server Management
/// # See Also
/// [Redis Server Management Commands](https://redis.io/commands/?group=server)
/// [ACL guide](https://redis.io/docs/manual/security/acl/)
pub trait ServerCommands<T>: PrepareCommand<T> {
    /// The command shows the available ACL categories if called without arguments.
    /// If a category name is given, the command shows all the Redis commands in the specified category.
    ///
    /// # Return
    /// A collection of ACL categories or a collection of commands inside a given category.
    ///
    /// # Errors
    /// The command may return an error if an invalid category name is given as argument.
    ///
    /// # See Also
    /// [<https://redis.io/commands/acl-cat/>](https://redis.io/commands/acl-cat/)
    fn acl_cat<C, CC>(&self, options: AclCatOptions) -> CommandResult<T, CC>
    where
        C: FromValue,
        CC: FromSingleValueArray<C>,
    {
        self.prepare_command(cmd("ACL").arg("CAT").arg(options))
    }

    /// Delete all the specified ACL users and terminate all
    /// the connections that are authenticated with such users.
    ///
    /// # Return
    /// The number of users that were deleted.
    /// This number will not always match the number of arguments since certain users may not exist.
    ///
    /// # See Also
    /// [<https://redis.io/commands/acl-deluser/>](https://redis.io/commands/acl-deluser/)
    fn acl_deluser<U, UU>(&self, usernames: UU) -> CommandResult<T, usize>
    where
        U: Into<BulkString>,
        UU: SingleArgOrCollection<U>,
    {
        self.prepare_command(cmd("ACL").arg("DELUSER").arg(usernames))
    }

    /// Simulate the execution of a given command by a given user.
    ///
    /// # Return
    /// OK on success.
    /// An error describing why the user can't execute the command.
    ///
    /// # See Also
    /// [<https://redis.io/commands/acl-dryrun/>](https://redis.io/commands/acl-dryrun/)
    fn acl_dryrun<U, C, R>(
        &self,
        username: U,
        command: C,
        options: AclDryRunOptions,
    ) -> CommandResult<T, R>
    where
        U: Into<BulkString>,
        C: Into<BulkString>,
        R: FromValue,
    {
        self.prepare_command(
            cmd("ACL")
                .arg("DRYRUN")
                .arg(username)
                .arg(command)
                .arg(options),
        )
    }

    /// Generates a password starting from /dev/urandom if available,
    /// otherwise (in systems without /dev/urandom) it uses a weaker
    /// system that is likely still better than picking a weak password by hand.
    ///
    /// # Return
    /// by default 64 bytes string representing 256 bits of pseudorandom data.
    /// Otherwise if an argument if needed, the output string length is the number
    /// of specified bits (rounded to the next multiple of 4) divided by 4.
    ///
    /// # See Also
    /// [<https://redis.io/commands/acl-genpass/>](https://redis.io/commands/acl-genpass/)
    fn acl_genpass<R: FromValue>(&self, options: AclGenPassOptions) -> CommandResult<T, R> {
        self.prepare_command(cmd("ACL").arg("GENPASS").arg(options))
    }

    /// The command returns all the rules defined for an existing ACL user.
    ///
    /// # Return
    /// A collection of ACL rule definitions for the user.
    ///
    /// # See Also
    /// [<https://redis.io/commands/acl-getuser/>](https://redis.io/commands/acl-getuser/)
    fn acl_getuser<U, RR>(&self, username: U) -> CommandResult<T, RR>
    where
        U: Into<BulkString>,
        RR: FromKeyValueValueArray<String, Value>,
    {
        self.prepare_command(cmd("ACL").arg("GETUSER").arg(username))
    }

    /// The command shows the currently active ACL rules in the Redis server.
    ///
    /// # Return
    /// An array of strings.
    /// Each line in the returned array defines a different user, and the
    /// format is the same used in the redis.conf file or the external ACL file
    ///
    /// # See Also
    /// [<https://redis.io/commands/acl-list/>](https://redis.io/commands/acl-list/)
    fn acl_list(&self) -> CommandResult<T, Vec<String>> {
        self.prepare_command(cmd("ACL").arg("LIST"))
    }

    /// When Redis is configured to use an ACL file (with the aclfile configuration option),
    /// this command will reload the ACLs from the file, replacing all the current ACL rules
    /// with the ones defined in the file.
    ///
    /// # Return
    /// An array of strings.
    /// Each line in the returned array defines a different user, and the
    /// format is the same used in the redis.conf file or the external ACL file
    ///
    /// # Errors
    /// The command may fail with an error for several reasons:
    /// - if the file is not readable,
    /// - if there is an error inside the file, and in such case the error will be reported to the user in the error.
    /// - Finally the command will fail if the server is not configured to use an external ACL file.
    ///
    /// # See Also
    /// [<https://redis.io/commands/acl-load/>](https://redis.io/commands/acl-load/)
    fn acl_load(&self) -> CommandResult<T, ()> {
        self.prepare_command(cmd("ACL").arg("LOAD"))
    }

    /// The command shows a list of recent ACL security events
    ///
    /// # Return
    /// A key/value collection of ACL security events.
    /// Empty collection when called with the [`reset`](crate::AclLogOptions::reset) option
    ///
    /// # See Also
    /// [<https://redis.io/commands/acl-log/>](https://redis.io/commands/acl-log/)
    fn acl_log<EE>(&self, options: AclLogOptions) -> CommandResult<T, Vec<EE>>
    where
        EE: FromKeyValueValueArray<String, Value>,
    {
        self.prepare_command(cmd("ACL").arg("LOG").arg(options))
    }

    /// When Redis is configured to use an ACL file (with the aclfile configuration option),
    /// this command will save the currently defined ACLs from the server memory to the ACL file.
    ///
    /// # Errors
    /// The command may fail with an error for several reasons:
    /// - if the file cannot be written
    /// - if the server is not configured to use an external ACL file.
    ///
    /// # See Also
    /// [<https://redis.io/commands/acl-save/>](https://redis.io/commands/acl-save/)
    fn acl_save(&self) -> CommandResult<T, ()> {
        self.prepare_command(cmd("ACL").arg("SAVE"))
    }

    /// Create an ACL user with the specified rules or modify the rules of an existing user.
    ///
    /// # Errors
    /// If the rules contain errors, the error is returned.
    ///
    /// # See Also
    /// [<https://redis.io/commands/acl-setuser/>](https://redis.io/commands/acl-setuser/)
    fn acl_setuser<U, R, RR>(&self, username: U, rules: RR) -> CommandResult<T, ()>
    where
        U: Into<BulkString>,
        R: Into<BulkString>,
        RR: SingleArgOrCollection<R>,
    {
        self.prepare_command(cmd("ACL").arg("SETUSER").arg(username).arg(rules))
    }

    /// The command shows a list of all the usernames of the currently configured users in the Redis ACL system.
    ///
    /// # Return
    /// A collection of usernames
    ///
    /// # See Also
    /// [<https://redis.io/commands/acl-users/>](https://redis.io/commands/acl-users/)
    fn acl_users<U, UU>(&self) -> CommandResult<T, UU>
    where
        U: FromValue,
        UU: FromSingleValueArray<U>,
    {
        self.prepare_command(cmd("ACL").arg("USERS"))
    }

    /// Return the username the current connection is authenticated with.
    ///
    /// # Return
    /// The username of the current connection.
    ///
    /// # See Also
    /// [<https://redis.io/commands/acl-whoami/>](https://redis.io/commands/acl-whoami/)
    fn acl_whoami<U: FromValue>(&self) -> CommandResult<T, U> {
        self.prepare_command(cmd("ACL").arg("WHOAMI"))
    }

    /// Return an array with details about every Redis command.
    ///
    /// # Return
    /// A nested list of command details.
    /// The order of commands in the array is random.
    ///
    /// # See Also
    /// [<https://redis.io/commands/command/>](https://redis.io/commands/command/)
    fn command(&self) -> CommandResult<T, Vec<CommandInfo>> {
        self.prepare_command(cmd("COMMAND"))
    }

    /// Number of total commands in this Redis server.
    ///
    /// # Return
    /// number of commands returned by [`command`](crate::ServerCommands::command)
    ///
    /// # See Also
    /// [<https://redis.io/commands/command-count/>](https://redis.io/commands/command-count/)
    fn command_count(&self) -> CommandResult<T, usize> {
        self.prepare_command(cmd("COMMAND").arg("COUNT"))
    }

    /// Number of total commands in this Redis server.
    ///
    /// # Return
    /// map key=command name, value=command doc
    ///
    /// # See Also
    /// [<https://redis.io/commands/command-docs/>](https://redis.io/commands/command-docs/)
    fn command_docs<N, NN, DD>(&self, command_names: NN) -> CommandResult<T, DD>
    where
        N: Into<BulkString>,
        NN: SingleArgOrCollection<N>,
        DD: FromKeyValueValueArray<String, CommandDoc>,
    {
        self.prepare_command(cmd("COMMAND").arg("DOCS").arg(command_names))
    }

    /// A helper command to let you find the keys from a full Redis command.
    ///
    /// # Return
    /// list of keys from your command.
    ///
    /// # See Also
    /// [<https://redis.io/commands/command-_getkeys/>](https://redis.io/commands/command-_getkeys/)
    fn command_getkeys<A, AA, KK>(&self, args: AA) -> CommandResult<T, KK>
    where
        A: Into<BulkString>,
        AA: SingleArgOrCollection<A>,
        KK: FromSingleValueArray<String>,
    {
        self.prepare_command(cmd("COMMAND").arg("GETKEYS").arg(args))
    }

    /// A helper command to let you find the keys from a full Redis command together with flags indicating what each key is used for.
    ///
    /// # Return
    /// map of keys with their flags from your command.
    ///
    /// # See Also
    /// [<https://redis.io/commands/command-getkeysandflags/>](https://redis.io/commands/command-getkeysandflags/)
    fn command_getkeysandflags<A, AA, KK>(&self, args: AA) -> CommandResult<T, KK>
    where
        A: Into<BulkString>,
        AA: SingleArgOrCollection<A>,
        KK: FromKeyValueValueArray<String, Vec<String>>,
    {
        self.prepare_command(cmd("COMMAND").arg("GETKEYSANDFLAGS").arg(args))
    }

    /// Return an array with details about multiple Redis command.
    ///
    /// # Return
    /// A nested list of command details.
    ///
    /// # See Also
    /// [<https://redis.io/commands/command-info/>](https://redis.io/commands/command-info/)
    fn command_info<N, NN>(&self, command_names: NN) -> CommandResult<T, Vec<CommandInfo>>
    where
        N: Into<BulkString>,
        NN: SingleArgOrCollection<N>,
    {
        self.prepare_command(cmd("COMMAND").arg("INFO").arg(command_names))
    }

    /// Return an array of the server's command names based on optional filters
    ///
    /// # Return
    /// an array of the server's command names.
    ///
    /// # See Also
    /// [<https://redis.io/commands/command-list/>](https://redis.io/commands/command-list/)
    fn command_list<CC>(&self, options: CommandListOptions) -> CommandResult<T, CC>
    where
        CC: FromSingleValueArray<String>,
    {
        self.prepare_command(cmd("COMMAND").arg("LIST").arg(options))
    }

    /// Used to read the configuration parameters of a running Redis server.
    ///
    /// For every key that does not hold a string value or does not exist,
    /// the special value nil is returned. Because of this, the operation never fails.
    ///
    /// # Return
    /// Array reply: collection of the requested params with their matching values.
    ///
    /// # See Also
    /// [<https://redis.io/commands/config-get/>](https://redis.io/commands/config-get/)
    #[must_use]
    fn config_get<P, PP, V, VV>(&self, params: PP) -> CommandResult<T, VV>
    where
        P: Into<BulkString>,
        PP: SingleArgOrCollection<P>,
        V: FromValue,
        VV: FromKeyValueValueArray<String, V>,
    {
        self.prepare_command(cmd("CONFIG").arg("GET").arg(params))
    }

    /// Resets the statistics reported by Redis using the [`info`](crate::ServerCommands::info) command.
    ///
    /// # See Also
    /// [<https://redis.io/commands/config-resetstat/>](https://redis.io/commands/config-resetstat/)
    #[must_use]
    fn config_resetstat(&self) -> CommandResult<T, ()> {
        self.prepare_command(cmd("CONFIG").arg("RESETSTAT"))
    }

    /// Rewrites the redis.conf file the server was started with,
    /// applying the minimal changes needed to make it reflect the configuration currently used by the server,
    /// which may be different compared to the original one because of the use of the
    /// [`config_set`](crate::ServerCommands::config_set) command.
    ///
    /// # See Also
    /// [<https://redis.io/commands/config-rewrite/>](https://redis.io/commands/config-rewrite/)
    #[must_use]
    fn config_rewrite(&self) -> CommandResult<T, ()> {
        self.prepare_command(cmd("CONFIG").arg("REWRITE"))
    }

    /// Used in order to reconfigure the server at run time without the need to restart Redis.
    ///
    /// # See Also
    /// [<https://redis.io/commands/config-set/>](https://redis.io/commands/config-set/)
    #[must_use]
    fn config_set<P, V, C>(&self, configs: C) -> CommandResult<T, ()>
    where
        P: Into<BulkString>,
        V: Into<BulkString>,
        C: KeyValueArgOrCollection<P, V>,
    {
        self.prepare_command(cmd("CONFIG").arg("SET").arg(configs))
    }

    /// Return the number of keys in the currently-selected database.
    ///
    /// # See Also
    /// [<https://redis.io/commands/dbsize/>](https://redis.io/commands/dbsize/)
    #[must_use]
    fn dbsize(&self) -> CommandResult<T, usize> {
        self.prepare_command(cmd("DBSIZE"))
    }

    /// This command will start a coordinated failover between
    /// the currently-connected-to master and one of its replicas.
    ///
    /// # See Also
    /// [<https://redis.io/commands/failover/>](https://redis.io/commands/failover/)
    #[must_use]
    fn failover(&self, options: FailOverOptions) -> CommandResult<T, ()> {
        self.prepare_command(cmd("FAILOVER").arg(options))
    }

    /// Delete all the keys of the currently selected DB.
    ///
    /// # See Also
    /// [<https://redis.io/commands/flushdb/>](https://redis.io/commands/flushdb/)
    #[must_use]
    fn flushdb(&self, flushing_mode: FlushingMode) -> CommandResult<T, ()> {
        self.prepare_command(cmd("FLUSHDB").arg(flushing_mode))
    }

    /// Delete all the keys of all the existing databases, not just the currently selected one.
    ///
    /// # See Also
    /// [<https://redis.io/commands/flushall/>](https://redis.io/commands/flushall/)
    #[must_use]
    fn flushall(&self, flushing_mode: FlushingMode) -> CommandResult<T, ()> {
        self.prepare_command(cmd("FLUSHALL").arg(flushing_mode))
    }

    /// This command returns information and statistics about the server
    /// in a format that is simple to parse by computers and easy to read by humans.
    ///
    /// # See Also
    /// [<https://redis.io/commands/info/>](https://redis.io/commands/info/)
    #[must_use]
    fn info<SS>(&self, sections: SS) -> CommandResult<T, String>
    where
        SS: SingleArgOrCollection<InfoSection>,
    {
        self.prepare_command(cmd("INFO").arg(sections))
    }

    /// Return the UNIX TIME of the last DB save executed with success.
    ///
    /// # See Also
    /// [<https://redis.io/commands/lastsave/>](https://redis.io/commands/lastsave/)
    #[must_use]
    fn lastsave(&self) -> CommandResult<T, u64> {
        self.prepare_command(cmd("LASTSAVE"))
    }

    /// This command reports about different latency-related issues and advises about possible remedies.
    ///
    /// # Return
    /// String report
    ///
    /// # See Also
    /// [<https://redis.io/commands/latency-doctor/>](https://redis.io/commands/latency-doctor/)
    #[must_use]
    fn latency_doctor(&self) -> CommandResult<T, String> {
        self.prepare_command(cmd("LATENCY").arg("DOCTOR"))
    }

    /// Produces an ASCII-art style graph for the specified event.
    ///
    /// # Return
    /// String graph
    ///
    /// # See Also
    /// [<https://redis.io/commands/latency-graph/>](https://redis.io/commands/latency-graph/)
    #[must_use]
    fn latency_graph(&self, event: LatencyHistoryEvent) -> CommandResult<T, String> {
        self.prepare_command(cmd("LATENCY").arg("GRAPH").arg(event))
    }

    /// This command reports a cumulative distribution of latencies
    /// in the format of a histogram for each of the specified command names.
    ///
    /// # Return
    /// The command returns a map where each key is a command name, and each value is a CommandHistogram instance.
    ///
    /// # See Also
    /// [<https://redis.io/commands/latency-histogram/>](https://redis.io/commands/latency-histogram/)
    #[must_use]
    fn latency_histogram<C, CC, RR>(&self, commands: CC) -> CommandResult<T, RR>
    where
        C: Into<BulkString>,
        CC: SingleArgOrCollection<C>,
        RR: FromKeyValueValueArray<String, CommandHistogram>,
    {
        self.prepare_command(cmd("LATENCY").arg("HISTOGRAM").arg(commands))
    }

    /// This command returns the raw data of the event's latency spikes time series.
    ///
    /// # Return
    /// The command returns a collection where each element is a two elements tuple representing
    /// - the unix timestamp in seconds
    /// - the latency of the event in milliseconds
    ///
    /// # See Also
    /// [<https://redis.io/commands/latency-history/>](https://redis.io/commands/latency-history/)
    #[must_use]
    fn latency_history<RR>(&self, event: LatencyHistoryEvent) -> CommandResult<T, RR>
    where
        RR: FromSingleValueArray<(u32, u32)>,
    {
        self.prepare_command(cmd("LATENCY").arg("HISTORY").arg(event))
    }

    /// This command reports the latest latency events logged.
    ///
    /// # Return
    /// A collection of the latest latency events logged.
    /// Each reported event has the following fields:
    /// - Event name.
    /// - Unix timestamp of the latest latency spike for the event.
    /// - Latest event latency in millisecond.
    /// - All-time maximum latency for this event.
    ///
    /// "All-time" means the maximum latency since the Redis instance was started,
    /// or the time that events were [`reset`](crate::ConnectionCommands::reset).
    ///
    /// # See Also
    /// [<https://redis.io/commands/latency-latest/>](https://redis.io/commands/latency-latest/)
    #[must_use]
    fn latency_latest<RR>(&self) -> CommandResult<T, RR>
    where
        RR: FromSingleValueArray<(String, u32, u32, u32)>,
    {
        self.prepare_command(cmd("LATENCY").arg("LATEST"))
    }

    /// This command resets the latency spikes time series of all, or only some, events.
    ///
    /// # Return
    /// the number of event time series that were reset.
    ///
    /// # See Also
    /// [<https://redis.io/commands/latency-latest/>](https://redis.io/commands/latency-latest/)
    #[must_use]
    fn latency_reset<EE>(&self, events: EE) -> CommandResult<T, usize>
    where
        EE: SingleArgOrCollection<LatencyHistoryEvent>,
    {
        self.prepare_command(cmd("LATENCY").arg("RESET").arg(events))
    }

    /// The LOLWUT command displays the Redis version: however as a side effect of doing so,
    /// it also creates a piece of generative computer art that is different with each version of Redis.
    ///
    /// # Return
    /// the string containing the generative computer art, and a text with the Redis version.
    ///
    /// # See Also
    /// [<https://redis.io/commands/lolwut/>](https://redis.io/commands/lolwut/)
    #[must_use]
    fn lolwut(&self, options: LolWutOptions) -> CommandResult<T, String> {
        self.prepare_command(cmd("LOLWUT").arg(options))
    }

    /// This command reports about different memory-related issues that
    /// the Redis server experiences, and advises about possible remedies.
    ///
    /// # Return
    /// the string report.
    ///
    /// # See Also
    /// [<https://redis.io/commands/memory-doctor/>](https://redis.io/commands/memory-doctor/)
    #[must_use]
    fn memory_doctor(&self) -> CommandResult<T, String> {
        self.prepare_command(cmd("MEMORY").arg("DOCTOR"))
    }

    /// This command provides an internal statistics report from the memory allocator.
    ///
    /// # Return
    /// the memory allocator's internal statistics report.
    ///
    /// # See Also
    /// [<https://redis.io/commands/memory-malloc-stats/>](https://redis.io/commands/memory-malloc-stats/)
    #[must_use]
    fn memory_malloc_stats(&self) -> CommandResult<T, String> {
        self.prepare_command(cmd("MEMORY").arg("MALLOC-STATS"))
    }

    /// This command attempts to purge dirty pages so these can be reclaimed by the allocator.
    ///
    /// # See Also
    /// [<https://redis.io/commands/memory-purge/>](https://redis.io/commands/memory-purge/)
    #[must_use]
    fn memory_purge(&self) -> CommandResult<T, ()> {
        self.prepare_command(cmd("MEMORY").arg("PURGE"))
    }

    /// This command returns information about the memory usage of the server.
    ///
    /// # Return
    /// the memory allocator's internal statistics report.
    ///
    /// # See Also
    /// [<https://redis.io/commands/memory-stats/>](https://redis.io/commands/memory-stats/)
    #[must_use]
    fn memory_stats(&self) -> CommandResult<T, MemoryStats> {
        self.prepare_command(cmd("MEMORY").arg("STATS"))
    }

    /// This command reports the number of bytes that a key and its value require to be stored in RAM.
    ///
    /// # Return
    /// the memory usage in bytes, or None when the key does not exist.
    ///
    /// # See Also
    /// [<https://redis.io/commands/memory-usage/>](https://redis.io/commands/memory-usage/)
    #[must_use]
    fn memory_usage<K>(
        &self,
        key: K,
        options: MemoryUsageOptions,
    ) -> CommandResult<T, Option<usize>>
    where
        K: Into<BulkString>,
    {
        self.prepare_command(cmd("MEMORY").arg("USAGE").arg(key).arg(options))
    }

    /// Returns information about the modules loaded to the server.
    ///
    /// # Return
    /// list of loaded modules.
    /// Each element in the list represents a module as an instance of [`ModuleInfo`](crate::ModuleInfo)
    ///
    /// # See Also
    /// [<https://redis.io/commands/module-list/>](https://redis.io/commands/module-list/)
    #[must_use]
    fn module_list<MM>(&self) -> CommandResult<T, MM>
    where
        MM: FromSingleValueArray<ModuleInfo>,
    {
        self.prepare_command(cmd("MODULE").arg("LIST"))
    }

    /// Loads a module from a dynamic library at runtime.
    ///
    /// # See Also
    /// [<https://redis.io/commands/module-load/>](https://redis.io/commands/module-load/)
    #[must_use]
    fn module_load<P>(&self, path: P, options: ModuleLoadOptions) -> CommandResult<T, ()>
    where
        P: Into<BulkString>,
    {
        self.prepare_command(cmd("MODULE").arg("LOADEX").arg(path).arg(options))
    }

    /// Unloads a module.
    ///
    /// # See Also
    /// [<https://redis.io/commands/module-unload/>](https://redis.io/commands/module-unload/)
    #[must_use]
    fn module_unload<N>(&self, name: N) -> CommandResult<T, ()>
    where
        N: Into<BulkString>,
    {
        self.prepare_command(cmd("MODULE").arg("UNLOAD").arg(name))
    }

    /// Debugging command that streams back every command processed by the Redis server.
    ///
    /// # See Also
    /// [<https://redis.io/commands/monitor/>](https://redis.io/commands/monitor/)
    #[must_use]
    fn monitor(&self) -> Future<MonitorStream>;

    /// This command can change the replication settings of a replica on the fly.
    ///
    /// # See Also
    /// [<https://redis.io/commands/replicaof/>](https://redis.io/commands/replicaof/)
    #[must_use]
    fn replicaof(&self, options: ReplicaOfOptions) -> CommandResult<T, ()> {
        self.prepare_command(cmd("REPLICAOF").arg(options))
    }

    /// Provide information on the role of a Redis instance in the context of replication,
    /// by returning if the instance is currently a `master`, `slave`, or `sentinel`.
    ///
    /// # See Also
    /// [<https://redis.io/commands/role/>](https://redis.io/commands/role/)
    #[must_use]
    fn role(&self) -> CommandResult<T, RoleResult> {
        self.prepare_command(cmd("ROLE"))
    }

    /// This command performs a synchronous save of the dataset producing a point in time snapshot
    /// of all the data inside the Redis instance, in the form of an RDB file.
    ///
    /// # See Also
    /// [<https://redis.io/commands/save/>](https://redis.io/commands/save/)
    #[must_use]
    fn save(&self) -> CommandResult<T, ()> {
        self.prepare_command(cmd("SAVE"))
    }

    /// Shutdown the server
    ///
    /// # See Also
    /// [<https://redis.io/commands/shutdown/>](https://redis.io/commands/shutdown/)
    #[must_use]
    fn shutdown(&self, options: ShutdownOptions) -> CommandResult<T, ()> {
        self.prepare_command(cmd("SHUTDOWN").arg(options))
    }

    /// This command returns entries from the slow log in chronological order.
    ///
    /// # See Also
    /// [<https://redis.io/commands/slowlog-get/>](https://redis.io/commands/slowlog-get/)
    #[must_use]
    fn slowlog_get(&self, options: SlowLogOptions) -> CommandResult<T, Vec<SlowLogEntry>> {
        self.prepare_command(cmd("SLOWLOG").arg("GET").arg(options))
    }

    /// This command returns the current number of entries in the slow log.
    ///
    /// # See Also
    /// [<https://redis.io/commands/slowlog-len/>](https://redis.io/commands/slowlog-len/)
    #[must_use]
    fn slowlog_len(&self) -> CommandResult<T, usize> {
        self.prepare_command(cmd("SLOWLOG").arg("LEN"))
    }

    /// This command resets the slow log, clearing all entries in it.
    ///
    /// # See Also
    /// [<https://redis.io/commands/slowlog-reset/>](https://redis.io/commands/slowlog-reset/)
    #[must_use]
    fn slowlog_reset(&self) -> CommandResult<T, ()> {
        self.prepare_command(cmd("SLOWLOG").arg("RESET"))
    }

    /// This command swaps two Redis databases, 
    /// so that immediately all the clients connected to a given database 
    /// will see the data of the other database, and the other way around.
    ///
    /// # See Also
    /// [<https://redis.io/commands/swapdb/>](https://redis.io/commands/swapdb/)
    #[must_use]
    fn swapdb(&self, index1: usize, index2: usize) -> CommandResult<T, ()> {
        self.prepare_command(cmd("SWAPDB").arg(index1).arg(index2))
    }

    /// The TIME command returns the current server time as a two items lists:
    /// a Unix timestamp and the amount of microseconds already elapsed in the current second.
    ///
    /// # See Also
    /// [<https://redis.io/commands/time/>](https://redis.io/commands/time/)
    #[must_use]
    fn time(&self) -> CommandResult<T, (u32, u32)> {
        self.prepare_command(cmd("TIME"))
    }
}

/// Database flushing mode
pub enum FlushingMode {
    Default,
    /// Flushes the database(s) asynchronously
    Async,
    /// Flushed the database(s) synchronously
    Sync,
}

impl Default for FlushingMode {
    fn default() -> Self {
        FlushingMode::Default
    }
}

impl IntoArgs for FlushingMode {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        match self {
            FlushingMode::Default => args,
            FlushingMode::Async => args.arg("ASYNC"),
            FlushingMode::Sync => args.arg("SYNC"),
        }
    }
}

/// Options for the [`acl_cat`](crate::ServerCommands::acl_cat) command
#[derive(Default)]
pub struct AclCatOptions {
    command_args: CommandArgs,
}

impl AclCatOptions {
    #[must_use]
    pub fn category_name<C: Into<BulkString>>(self, category_name: C) -> Self {
        Self {
            command_args: self.command_args.arg(category_name),
        }
    }
}

impl IntoArgs for AclCatOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}

/// Options for the [`acl_dryrun`](crate::ServerCommands::acl_dryrun) command
#[derive(Default)]
pub struct AclDryRunOptions {
    command_args: CommandArgs,
}

impl AclDryRunOptions {
    #[must_use]
    pub fn arg<A, AA>(self, args: AA) -> Self
    where
        A: Into<BulkString>,
        AA: SingleArgOrCollection<A>,
    {
        Self {
            command_args: self.command_args.arg(args),
        }
    }
}

impl IntoArgs for AclDryRunOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}

/// Options for the [`acl_genpass`](crate::ServerCommands::acl_genpass) command
#[derive(Default)]
pub struct AclGenPassOptions {
    command_args: CommandArgs,
}

impl AclGenPassOptions {
    /// The command output is a hexadecimal representation of a binary string.
    /// By default it emits 256 bits (so 64 hex characters).
    /// The user can provide an argument in form of number of bits to emit from 1 to 1024 to change the output length.
    /// Note that the number of bits provided is always rounded to the next multiple of 4.
    /// So for instance asking for just 1 bit password will result in 4 bits to be emitted, in the form of a single hex character.
    #[must_use]
    pub fn bits(self, bits: usize) -> Self {
        Self {
            command_args: self.command_args.arg(bits),
        }
    }
}

impl IntoArgs for AclGenPassOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}

/// Options for the [`acl_log`](crate::ServerCommands::acl_log) command
#[derive(Default)]
pub struct AclLogOptions {
    command_args: CommandArgs,
}

impl AclLogOptions {
    /// This optional argument specifies how many entries to show.
    /// By default up to ten failures are returned.
    #[must_use]
    pub fn count(self, count: usize) -> Self {
        Self {
            command_args: self.command_args.arg(count),
        }
    }

    /// The special RESET argument clears the log.
    #[must_use]
    pub fn reset(self) -> Self {
        Self {
            command_args: self.command_args.arg("RESET"),
        }
    }
}

impl IntoArgs for AclLogOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}

/// Command info result for the [`command`](crate::ServerCommands::command) command.
#[derive(Debug)]
pub struct CommandInfo {
    /// This is the command's name in lowercase.
    pub name: String,
    /// Arity is the number of arguments a command expects. It follows a simple pattern:
    /// - A positive integer means a fixed number of arguments.
    /// - A negative integer means a minimal number of arguments.
    pub arity: isize,
    /// Command flags are an array.
    /// See [COMMAND documentation](https://redis.io/commands/command/) for the list of flags
    pub flags: Vec<String>,
    /// The position of the command's first key name argument.
    /// For most commands, the first key's position is 1. Position 0 is always the command name itself.
    pub first_key: usize,
    /// The position of the command's last key name argument.
    pub last_key: isize,
    /// The step, or increment, between the first key and the position of the next key.
    pub step: usize,
    /// [From Redis 6.0] This is an array of simple strings that are the ACL categories to which the command belongs.
    pub acl_categories: Vec<String>,
    /// [From Redis 7.0] Helpful information about the command. To be used by clients/proxies.
    /// See [<https://redis.io/docs/reference/command-tips/>](https://redis.io/docs/reference/command-tips/)
    pub command_tips: Vec<CommandTip>,
    /// [From Redis 7.0] This is an array consisting of the command's key specifications.
    /// See [<https://redis.io/docs/reference/key-specs/>](https://redis.io/docs/reference/key-specs/)
    pub key_specifications: Vec<KeySpecification>,
    pub sub_commands: Vec<CommandInfo>,
}

impl FromValue for CommandInfo {
    fn from_value(value: Value) -> Result<Self> {
        let values: Vec<Value> = value.into()?;
        let mut iter = values.into_iter();

        match (
            iter.next(),
            iter.next(),
            iter.next(),
            iter.next(),
            iter.next(),
            iter.next(),
            iter.next(),
            iter.next(),
            iter.next(),
            iter.next(),
        ) {
            (
                Some(name),
                Some(arity),
                Some(flags),
                Some(first_key),
                Some(last_key),
                Some(step),
                Some(acl_categories),
                Some(command_tips),
                Some(key_specifications),
                Some(sub_commands),
            ) => Ok(Self {
                name: name.into()?,
                arity: arity.into()?,
                flags: flags.into()?,
                first_key: first_key.into()?,
                last_key: last_key.into()?,
                step: step.into()?,
                acl_categories: acl_categories.into()?,
                command_tips: command_tips.into()?,
                key_specifications: key_specifications.into()?,
                sub_commands: sub_commands.into()?,
            }),
            (
                Some(name),
                Some(arity),
                Some(flags),
                Some(first_key),
                Some(last_key),
                Some(step),
                Some(acl_categories),
                None,
                None,
                None,
            ) => Ok(Self {
                name: name.into()?,
                arity: arity.into()?,
                flags: flags.into()?,
                first_key: first_key.into()?,
                last_key: last_key.into()?,
                step: step.into()?,
                acl_categories: acl_categories.into()?,
                command_tips: Vec::new(),
                key_specifications: Vec::new(),
                sub_commands: Vec::new(),
            }),
            (
                Some(name),
                Some(arity),
                Some(flags),
                Some(first_key),
                Some(last_key),
                Some(step),
                None,
                None,
                None,
                None,
            ) => Ok(Self {
                name: name.into()?,
                arity: arity.into()?,
                flags: flags.into()?,
                first_key: first_key.into()?,
                last_key: last_key.into()?,
                step: step.into()?,
                acl_categories: Vec::new(),
                command_tips: Vec::new(),
                key_specifications: Vec::new(),
                sub_commands: Vec::new(),
            }),
            _ => Err(Error::Client(
                "Cannot parse CommandInfo from result".to_owned(),
            )),
        }

        //let (name, arity, flags, first_key, last_key, step, acl_categories, command_tips, key_specifications, sub_commands)
    }
}

/// Get additional information about a command
/// See <https://redis.io/docs/reference/command-tips/>
#[derive(Debug)]
pub enum CommandTip {
    NonDeterministricOutput,
    NonDeterministricOutputOrder,
    RequestPolicy(RequestPolicy),
    ResponsePolicy(ResponsePolicy),
}

impl FromValue for CommandTip {
    fn from_value(value: Value) -> Result<Self> {
        let tip: String = value.into()?;
        match tip.as_str() {
            "nondeterministic_output" => Ok(CommandTip::NonDeterministricOutput),
            "nondeterministic_output_order" => Ok(CommandTip::NonDeterministricOutputOrder),
            _ => {
                let mut parts = tip.split(':');
                match (parts.next(), parts.next(), parts.next()) {
                    (Some("request_policy"), Some(policy), None) => {
                        Ok(CommandTip::RequestPolicy(RequestPolicy::from_str(policy)?))
                    }
                    (Some("response_policy"), Some(policy), None) => Ok(
                        CommandTip::ResponsePolicy(ResponsePolicy::from_str(policy)?),
                    ),
                    _ => Err(Error::Client(
                        "Cannot parse CommandTip from result".to_owned(),
                    )),
                }
            }
        }
    }
}

#[derive(Debug)]
pub enum RequestPolicy {
    AllNodes,
    AllShards,
    MultiShard,
    Special,
}

impl FromStr for RequestPolicy {
    type Err = Error;

    fn from_str(str: &str) -> Result<Self> {
        match str {
            "all_nodes" => Ok(RequestPolicy::AllNodes),
            "all_shards" => Ok(RequestPolicy::AllShards),
            "multi_shard" => Ok(RequestPolicy::MultiShard),
            "special" => Ok(RequestPolicy::Special),
            _ => Err(Error::Client(
                "Cannot parse RequestPolicy from result".to_owned(),
            )),
        }
    }
}

#[derive(Debug)]
pub enum ResponsePolicy {
    OneSucceeded,
    AllSucceeded,
    AggLogicalAnd,
    AggLogicalOr,
    AggMin,
    AggMax,
    AggSum,
    Special,
}

impl FromStr for ResponsePolicy {
    type Err = Error;

    fn from_str(str: &str) -> Result<Self> {
        match str {
            "one_succeeded" => Ok(ResponsePolicy::OneSucceeded),
            "all_succeeded" => Ok(ResponsePolicy::AllSucceeded),
            "agg_logical_and" => Ok(ResponsePolicy::AggLogicalAnd),
            "agg_logical_or" => Ok(ResponsePolicy::AggLogicalOr),
            "agg_min" => Ok(ResponsePolicy::AggMin),
            "agg_max" => Ok(ResponsePolicy::AggMax),
            "agg_sum" => Ok(ResponsePolicy::AggSum),
            "special" => Ok(ResponsePolicy::Special),
            _ => Err(Error::Client(
                "Cannot parse ResponsePolicy from result".to_owned(),
            )),
        }
    }
}

/// Key specifications of a command for the [`command`](crate::ServerCommands::command) command.
#[derive(Debug)]
pub struct KeySpecification {
    pub begin_search: BeginSearch,
    pub find_keys: FindKeys,
    pub flags: Vec<String>,
    pub notes: String,
}

impl FromValue for KeySpecification {
    fn from_value(value: Value) -> Result<Self> {
        let mut values: HashMap<String, Value> = value.into()?;

        let notes: String = match values.remove("notes") {
            Some(notes) => notes.into()?,
            None => "".to_owned(),
        };

        Ok(Self {
            begin_search: values.remove_with_result("begin_search")?.into()?,
            find_keys: values.remove_with_result("find_keys")?.into()?,
            flags: values.remove_with_result("flags")?.into()?,
            notes,
        })
    }
}

#[derive(Debug)]
pub enum BeginSearch {
    Index(usize),
    Keyword { keyword: String, start_from: isize },
    Unknown,
}

impl FromValue for BeginSearch {
    fn from_value(value: Value) -> Result<Self> {
        let mut values: HashMap<String, Value> = value.into()?;

        let type_: String = values.remove_with_result("type")?.into()?;
        match type_.as_str() {
            "index" => {
                let mut spec: HashMap<String, Value> = values.remove_with_result("spec")?.into()?;
                Ok(BeginSearch::Index(
                    spec.remove_with_result("index")?.into()?,
                ))
            }
            "keyword" => {
                let mut spec: HashMap<String, Value> = values.remove_with_result("spec")?.into()?;
                Ok(BeginSearch::Keyword {
                    keyword: spec.remove_with_result("keyword")?.into()?,
                    start_from: spec.remove_with_result("startfrom")?.into()?,
                })
            }
            "unknown" => Ok(BeginSearch::Unknown),
            _ => Err(Error::Client(
                "Cannot parse BeginSearch from result".to_owned(),
            )),
        }
    }
}

#[derive(Debug)]
pub enum FindKeys {
    Range {
        last_key: isize,
        key_step: usize,
        limit: isize,
    },
    KeyEnum {
        key_num_idx: isize,
        first_key: isize,
        key_step: usize,
    },
    Unknown,
}

impl FromValue for FindKeys {
    fn from_value(value: Value) -> Result<Self> {
        let mut values: HashMap<String, Value> = value.into()?;

        let type_: String = values.remove_with_result("type")?.into()?;
        match type_.as_str() {
            "range" => {
                let mut spec: HashMap<String, Value> = values.remove_with_result("spec")?.into()?;
                Ok(FindKeys::Range {
                    last_key: spec.remove_with_result("lastkey")?.into()?,
                    key_step: spec.remove_with_result("keystep")?.into()?,
                    limit: spec.remove_with_result("limit")?.into()?,
                })
            }
            "keynum" => {
                let mut spec: HashMap<String, Value> = values.remove_with_result("spec")?.into()?;
                Ok(FindKeys::KeyEnum {
                    key_num_idx: spec.remove_with_result("keynumidx")?.into()?,
                    first_key: spec.remove_with_result("firstkey")?.into()?,
                    key_step: spec.remove_with_result("keystep")?.into()?,
                })
            }
            "unknown" => Ok(FindKeys::Unknown),
            _ => Err(Error::Client(
                "Cannot parse BeginSearch from result".to_owned(),
            )),
        }
    }
}

/// Command doc result for the [`command_docs`](crate::ServerCommands::command_docs) command
#[derive(Debug, Default)]
pub struct CommandDoc {
    /// short command description.
    pub summary: String,
    /// the Redis version that added the command (or for module commands, the module version).
    pub since: String,
    /// he functional group to which the command belongs.
    pub group: String,
    /// a short explanation about the command's time complexity.
    pub complexity: String,
    /// an array of documentation flags. Possible values are:
    /// - `deprecated`: the command is deprecated.
    /// - `syscmd`: a system command that isn't meant to be called by users.
    pub doc_flags: Vec<CommandDocFlag>,
    /// the Redis version that deprecated the command (or for module commands, the module version).
    pub deprecated_since: String,
    /// the alternative for a deprecated command.
    pub replaced_by: String,
    /// an array of historical notes describing changes to the command's behavior or arguments.
    pub history: Vec<HistoricalNote>,
    /// an array of [`command arguments`](https://redis.io/docs/reference/command-arguments/)
    pub arguments: Vec<CommandArgument>,
}

impl FromValue for CommandDoc {
    fn from_value(value: Value) -> Result<Self> {
        let mut values: HashMap<String, Value> = value.into()?;

        Ok(Self {
            summary: values.remove_with_result("summary")?.into()?,
            since: values.remove_with_result("since")?.into()?,
            group: values.remove_with_result("group")?.into()?,
            complexity: values.remove_with_result("complexity")?.into()?,
            doc_flags: values.remove_or_default("doc_flags").into()?,
            deprecated_since: values.remove_or_default("deprecated_since").into()?,
            replaced_by: values.remove_or_default("replaced_by").into()?,
            history: values.remove_or_default("history").into()?,
            arguments: values.remove_with_result("arguments")?.into()?,
        })
    }
}

/// Command documenation flag
#[derive(Debug)]
pub enum CommandDocFlag {
    /// the command is deprecated.
    Deprecated,
    /// a system command that isn't meant to be called by users.
    SystemCommand,
}

impl FromValue for CommandDocFlag {
    fn from_value(value: Value) -> Result<Self> {
        let f: String = value.into()?;

        match f.as_str() {
            "deprecated" => Ok(CommandDocFlag::Deprecated),
            "syscmd" => Ok(CommandDocFlag::SystemCommand),
            _ => Err(Error::Client(
                "Cannot parse CommandDocFlag from result".to_owned(),
            )),
        }
    }
}

#[derive(Debug)]
pub struct HistoricalNote {
    pub version: String,
    pub description: String,
}

impl FromValue for HistoricalNote {
    fn from_value(value: Value) -> Result<Self> {
        let (version, description): (String, String) = value.into()?;

        Ok(Self {
            version,
            description,
        })
    }
}

/// [`command argument`](https://redis.io/docs/reference/command-arguments/)
#[derive(Debug)]
pub struct CommandArgument {
    ///  the argument's name, always present.
    pub name: String,
    /// the argument's display string, present in arguments that have a displayable representation
    pub display_text: String,
    ///  the argument's type, always present.
    pub type_: CommandArgumentType,
    /// this value is available for every argument of the `key` type.
    /// t is a 0-based index of the specification in the command's [`key specifications`](https://redis.io/topics/key-specs)
    /// that corresponds to the argument.
    pub key_spec_index: usize,
    /// a constant literal that precedes the argument (user input) itself.
    pub token: String,
    /// a short description of the argument.
    pub summary: String,
    /// the debut Redis version of the argument (or for module commands, the module version).
    pub since: String,
    /// the Redis version that deprecated the command (or for module commands, the module version).
    pub deprecated_since: String,
    /// an array of argument flags.
    pub flags: Vec<ArgumentFlag>,
    /// the argument's value.
    pub value: Vec<String>,
}

impl FromValue for CommandArgument {
    fn from_value(value: Value) -> Result<Self> {
        let mut values: HashMap<String, Value> = value.into()?;

        Ok(Self {
            name: values.remove_with_result("name")?.into()?,
            display_text: values.remove_or_default("display_text").into()?,
            type_: values.remove_with_result("type")?.into()?,
            key_spec_index: values.remove_or_default("key_spec_index").into()?,
            token: values.remove_or_default("token").into()?,
            summary: values.remove_or_default("summary").into()?,
            since: values.remove_or_default("since").into()?,
            deprecated_since: values.remove_or_default("deprecated_since").into()?,
            flags: values.remove_or_default("flags").into()?,
            value: match values.remove_or_default("value") {
                value @ Value::BulkString(_) => vec![value.into()?],
                value @ Value::Array(_) => value.into()?,
                _ => {
                    return Err(Error::Client(
                        "Cannot parse CommandArgument from result".to_owned(),
                    ))
                }
            },
        })
    }
}

/// An argument must have one of the following types:
#[derive(Debug)]
pub enum CommandArgumentType {
    /// a string argument.
    String,
    /// an integer argument.
    Integer,
    /// a double-precision argument.
    Double,
    /// a string that represents the name of a key.
    Key,
    /// a string that represents a glob-like pattern.
    Pattern,
    /// an integer that represents a Unix timestamp.
    UnixTime,
    /// a token, i.e. a reserved keyword, which may or may not be provided.
    /// Not to be confused with free-text user input.
    PureToken,
    /// the argument is a container for nested arguments.
    /// This type enables choice among several nested arguments
    OneOf,
    /// the argument is a container for nested arguments.
    /// This type enables grouping arguments and applying a property (such as optional) to all
    Block,
}

impl FromValue for CommandArgumentType {
    fn from_value(value: Value) -> Result<Self> {
        let t: String = value.into()?;

        match t.as_str() {
            "string" => Ok(CommandArgumentType::String),
            "integer" => Ok(CommandArgumentType::Integer),
            "double" => Ok(CommandArgumentType::Double),
            "key" => Ok(CommandArgumentType::Key),
            "pattern" => Ok(CommandArgumentType::Pattern),
            "unix-time" => Ok(CommandArgumentType::UnixTime),
            "pure-token" => Ok(CommandArgumentType::PureToken),
            "oneof" => Ok(CommandArgumentType::OneOf),
            "block" => Ok(CommandArgumentType::Block),
            _ => Err(Error::Client(
                "Cannot parse CommandArgumentType from result".to_owned(),
            )),
        }
    }
}

/// Flag for a command argument
#[derive(Debug)]
pub enum ArgumentFlag {
    /// denotes that the argument is optional (for example, the GET clause of the SET command).
    Optional,
    /// denotes that the argument may be repeated (such as the key argument of DEL).
    Multiple,
    ///  denotes the possible repetition of the argument with its preceding token (see SORT's GET pattern clause).
    MultipleToken,
}

impl FromValue for ArgumentFlag {
    fn from_value(value: Value) -> Result<Self> {
        let f: String = value.into()?;

        match f.as_str() {
            "optional" => Ok(ArgumentFlag::Optional),
            "multiple" => Ok(ArgumentFlag::Multiple),
            "multiple-token" => Ok(ArgumentFlag::MultipleToken),
            _ => Err(Error::Client(
                "Cannot parse ArgumentFlag from result".to_owned(),
            )),
        }
    }
}

/// Options for the [`command_list`](crate::ServerCommands::command_list) command.
#[derive(Default)]
pub struct CommandListOptions {
    command_args: CommandArgs,
}

impl CommandListOptions {
    /// get the commands that belong to the module specified by `module-name`.
    #[must_use]
    pub fn filter_by_module_name<M: Into<BulkString>>(self, module_name: M) -> Self {
        Self {
            command_args: self
                .command_args
                .arg("FILTERBY")
                .arg("MODULE")
                .arg(module_name),
        }
    }

    /// get the commands in the [`ACL category`](https://redis.io/docs/manual/security/acl/#command-categories) specified by `category`.
    #[must_use]
    pub fn filter_by_acl_category<C: Into<BulkString>>(self, category: C) -> Self {
        Self {
            command_args: self
                .command_args
                .arg("FILTERBY")
                .arg("ACLCAT")
                .arg(category),
        }
    }

    /// get the commands that match the given glob-like `pattern`.
    #[must_use]
    pub fn filter_by_pattern<P: Into<BulkString>>(self, pattern: P) -> Self {
        Self {
            command_args: self
                .command_args
                .arg("FILTERBY")
                .arg("PATTERN")
                .arg(pattern),
        }
    }
}

impl IntoArgs for CommandListOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}

/// Options for the [`failover`](crate::ServerCommands::failover) command.
#[derive(Default)]
pub struct FailOverOptions {
    command_args: CommandArgs,
}

impl FailOverOptions {
    /// This option allows designating a specific replica, by its host and port, to failover to.
    #[must_use]
    pub fn to<H: Into<BulkString>>(self, host: H, port: u16) -> Self {
        Self {
            command_args: self.command_args.arg("TO").arg(host).arg(port),
        }
    }

    /// This option allows specifying a maximum time a master will wait in the waiting-for-sync state
    /// before aborting the failover attempt and rolling back.
    #[must_use]
    pub fn timeout(self, milliseconds: u64) -> Self {
        Self {
            command_args: self.command_args.arg("TIMEOUT").arg(milliseconds),
        }
    }

    /// If both the [`timeout`](crate::FailOverOptions::timeout) and [`to`](crate::FailOverOptions::to) options are set,
    /// the force flag can also be used to designate that that once the timeout has elapsed,
    /// the master should failover to the target replica instead of rolling back.
    #[must_use]
    pub fn force(self) -> Self {
        Self {
            command_args: self.command_args.arg("FORCE"),
        }
    }

    /// This command will abort an ongoing failover and return the master to its normal state.
    #[must_use]
    pub fn abort(self) -> Self {
        Self {
            command_args: self.command_args.arg("ABORT"),
        }
    }
}

impl IntoArgs for FailOverOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}

/// Section for the [`info`](crate::ServerCommands::info) command.
pub enum InfoSection {
    Server,
    Clients,
    Memory,
    Persistence,
    Stats,
    Replication,
    Cpu,
    Commandstats,
    Latencystats,
    Cluster,
    Keyspace,
    Modules,
    Errorstats,
    All,
    Default,
    Everything,
}

impl From<InfoSection> for BulkString {
    fn from(s: InfoSection) -> Self {
        match s {
            InfoSection::Server => BulkString::Str("server"),
            InfoSection::Clients => BulkString::Str("clients"),
            InfoSection::Memory => BulkString::Str("memory"),
            InfoSection::Persistence => BulkString::Str("persistence"),
            InfoSection::Stats => BulkString::Str("stats"),
            InfoSection::Replication => BulkString::Str("replication"),
            InfoSection::Cpu => BulkString::Str("cpu"),
            InfoSection::Commandstats => BulkString::Str("commandstats"),
            InfoSection::Latencystats => BulkString::Str("latencystats"),
            InfoSection::Cluster => BulkString::Str("cluster"),
            InfoSection::Keyspace => BulkString::Str("keyspace"),
            InfoSection::Modules => BulkString::Str("modules"),
            InfoSection::Errorstats => BulkString::Str("errorstats"),
            InfoSection::All => BulkString::Str("all"),
            InfoSection::Default => BulkString::Str("default"),
            InfoSection::Everything => BulkString::Str("everything"),
        }
    }
}

/// Latency history event for the [`latency_graph`](crate::ServerCommands::latency_graph)
/// & [`latency_history`](crate::ServerCommands::latency_history) commands.
pub enum LatencyHistoryEvent {
    ActiveDefragCycle,
    AofFsyncAlways,
    AofStat,
    AofRewriteDiffWrite,
    AofRename,
    AofWrite,
    AofWriteActiveChild,
    AofWriteAlone,
    AofWritePendingFsync,
    Command,
    ExpireCycle,
    EvictionCycle,
    EvictionDel,
    FastCommand,
    Fork,
    RdbUnlinkTempFile,
}

impl From<LatencyHistoryEvent> for BulkString {
    fn from(e: LatencyHistoryEvent) -> Self {
        match e {
            LatencyHistoryEvent::ActiveDefragCycle => "active-defrag-cycle".into(),
            LatencyHistoryEvent::AofFsyncAlways => "aof-fsync-always".into(),
            LatencyHistoryEvent::AofStat => "aof-stat".into(),
            LatencyHistoryEvent::AofRewriteDiffWrite => "aof-rewrite-diff-write".into(),
            LatencyHistoryEvent::AofRename => "aof-rename".into(),
            LatencyHistoryEvent::AofWrite => "aof-write".into(),
            LatencyHistoryEvent::AofWriteActiveChild => "aof-write-active-child".into(),
            LatencyHistoryEvent::AofWriteAlone => "aof-write-alone".into(),
            LatencyHistoryEvent::AofWritePendingFsync => "aof-write-pending-fsync".into(),
            LatencyHistoryEvent::Command => "command".into(),
            LatencyHistoryEvent::ExpireCycle => "expire-cycle".into(),
            LatencyHistoryEvent::EvictionCycle => "eviction-cycle".into(),
            LatencyHistoryEvent::EvictionDel => "eviction-del".into(),
            LatencyHistoryEvent::FastCommand => "fast-command".into(),
            LatencyHistoryEvent::Fork => "fork".into(),
            LatencyHistoryEvent::RdbUnlinkTempFile => "rdb-unlink-temp-file".into(),
        }
    }
}

/// Command Histogram for the [`latency_histogram`](crate::ServerCommands::latency_histogram) commands.
#[derive(Default)]
pub struct CommandHistogram {
    /// The total calls for that command.
    pub calls: usize,

    /// A map of time buckets:
    /// - Each bucket represents a latency range.
    /// - Each bucket covers twice the previous bucket's range.
    /// - Empty buckets are not printed.
    /// - The tracked latencies are between 1 microsecond and roughly 1 second.
    /// - Everything above 1 sec is considered +Inf.
    /// - At max there will be log2(1000000000)=30 buckets.
    pub histogram_usec: HashMap<u32, u32>,
}

impl FromValue for CommandHistogram {
    fn from_value(value: Value) -> Result<Self> {
        let mut values: HashMap<String, Value> = value.into()?;

        Ok(Self {
            calls: values.remove_with_result("calls")?.into()?,
            histogram_usec: values.remove_with_result("histogram_usec")?.into()?,
        })
    }
}

/// Options for the [`lolwut`](crate::ServerCommands::lolwut) command
#[derive(Default)]
pub struct LolWutOptions {
    command_args: CommandArgs,
}

impl LolWutOptions {
    #[must_use]
    pub fn version(self, version: usize) -> Self {
        Self {
            command_args: self.command_args.arg("VERSION").arg(version),
        }
    }

    #[must_use]
    pub fn optional_arg<A: Into<BulkString>>(self, arg: A) -> Self {
        Self {
            command_args: self.command_args.arg(arg),
        }
    }
}

impl IntoArgs for LolWutOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}

/// Result for the [`memory_stats`](crate::ServerCommands::memory_stats) command.
#[derive(Debug)]
pub struct MemoryStats {
    /// Peak memory consumed by Redis in bytes
    /// (see [`INFO`](https://redis.io/commands/info)'s used_memory_peak)
    pub peak_allocated: usize,

    /// Total number of bytes allocated by Redis using its allocator
    /// (see [`INFO`](https://redis.io/commands/info)'s used_memory)
    pub total_allocated: usize,

    /// Initial amount of memory consumed by Redis at startup in bytes
    /// (see [`INFO`](https://redis.io/commands/info)'s used_memory_startup)
    pub startup_allocated: usize,

    /// Size in bytes of the replication backlog
    /// (see [`INFO`](https://redis.io/commands/info)'s repl_backlog_active)
    pub replication_backlog: usize,

    /// The total size in bytes of all replicas overheads
    /// (output and query buffers, connection contexts)
    pub clients_slaves: usize,

    /// The total size in bytes of all clients overheads
    /// (output and query buffers, connection contexts)
    pub clients_normal: usize,

    /// Memory usage by cluster links
    /// (Added in Redis 7.0, see [`INFO`](https://redis.io/commands/info)'s mem_cluster_links).
    pub cluster_links: usize,

    /// The summed size in bytes of AOF related buffers.
    pub aof_buffer: usize,

    /// the summed size in bytes of the overheads of the Lua scripts' caches
    pub lua_caches: usize,

    /// the summed size in bytes of the overheads of the functions' caches
    pub functions_caches: usize,

    /// For each of the server's databases (key = db index),
    /// the overheads of the main and expiry dictionaries are reported in bytes
    pub databases: HashMap<usize, DatabaseOverhead>,

    /// The sum of all overheads, i.e. `startup.allocated`, `replication.backlog`,
    /// `clients.slaves`, `clients.normal`, `aof.buffer` and those of the internal data structures
    /// that are used in managing the Redis keyspace (see [`INFO`](https://redis.io/commands/info)'s used_memory_overhead)
    pub overhead_total: usize,

    /// The total number of keys stored across all databases in the server
    pub keys_count: usize,

    /// The ratio between net memory usage (`total.allocated` minus `startup.allocated`) and `keys.count`
    pub keys_bytes_per_key: usize,

    /// The size in bytes of the dataset, i.e. `overhead.total` subtracted from `total.allocated`
    ///  (see [`INFO`](https://redis.io/commands/info)'s used_memory_dataset)
    pub dataset_bytes: usize,

    /// The percentage of `dataset.bytes` out of the net memory usage
    pub dataset_percentage: f64,

    /// The percentage of `peak.allocated` out of `total.allocated`
    pub peak_percentage: f64,

    pub allocator_allocated: usize,

    pub allocator_active: usize,

    pub allocator_resident: usize,

    pub allocator_fragmentation_ratio: f64,

    pub allocator_fragmentation_bytes: usize,

    pub allocator_rss_ratio: f64,

    pub allocator_rss_bytes: usize,

    pub rss_overhead_ratio: f64,

    pub rss_overhead_bytes: usize,

    /// See [`INFO`](https://redis.io/commands/info)'s mem_fragmentation_ratio
    pub fragmentation: f64,

    pub fragmentation_bytes: usize,

    pub additional_stats: HashMap<String, Value>,
}

impl FromValue for MemoryStats {
    fn from_value(value: Value) -> Result<Self> {
        let mut values: HashMap<String, Value> = value.into()?;

        Ok(Self {
            peak_allocated: values.remove_or_default("peak.allocated").into()?,
            total_allocated: values.remove_or_default("total.allocated").into()?,
            startup_allocated: values.remove_or_default("startup.allocated").into()?,
            replication_backlog: values.remove_or_default("replication.backlog").into()?,
            clients_slaves: values.remove_or_default("clients.slaves").into()?,
            clients_normal: values.remove_or_default("clients.normal").into()?,
            cluster_links: values.remove_or_default("cluster.links").into()?,
            aof_buffer: values.remove_or_default("aof.buffer").into()?,
            lua_caches: values.remove_or_default("lua.caches").into()?,
            functions_caches: values.remove_or_default("functions.caches").into()?,
            databases: (0..16)
                .into_iter()
                .filter_map(|i| {
                    values
                        .remove(&format!("db.{i}"))
                        .map(|v| DatabaseOverhead::from_value(v).map(|o| (i, o)))
                })
                .collect::<Result<HashMap<usize, DatabaseOverhead>>>()?,
            overhead_total: values.remove_or_default("overhead.total").into()?,
            keys_count: values.remove_or_default("keys.count").into()?,
            keys_bytes_per_key: values.remove_or_default("keys.bytes-per-key").into()?,
            dataset_bytes: values.remove_or_default("dataset.bytes").into()?,
            dataset_percentage: values.remove_or_default("dataset.percentage").into()?,
            peak_percentage: values.remove_or_default("peak.percentage").into()?,
            allocator_allocated: values.remove_or_default("allocator.allocated").into()?,
            allocator_active: values.remove_or_default("allocator.active").into()?,
            allocator_resident: values.remove_or_default("allocator.resident").into()?,
            allocator_fragmentation_ratio: values
                .remove_or_default("allocator-fragmentation.ratio")
                .into()?,
            allocator_fragmentation_bytes: values
                .remove_or_default("allocator-fragmentation.bytes")
                .into()?,
            allocator_rss_ratio: values.remove_or_default("allocator-rss.ratio").into()?,
            allocator_rss_bytes: values.remove_or_default("allocator-rss.bytes").into()?,
            rss_overhead_ratio: values.remove_or_default("rss-overhead.ratio").into()?,
            rss_overhead_bytes: values.remove_or_default("rss-overhead.bytes").into()?,
            fragmentation: values.remove_or_default("fragmentation").into()?,
            fragmentation_bytes: values.remove_or_default("fragmentation.bytes").into()?,
            additional_stats: values,
        })
    }
}

#[derive(Debug)]
pub struct DatabaseOverhead {
    pub overhead_hashtable_main: usize,
    pub overhead_hashtable_expires: usize,
    pub overhead_hashtable_slot_to_keys: usize,
}

impl FromValue for DatabaseOverhead {
    fn from_value(value: Value) -> Result<Self> {
        let mut values: HashMap<String, Value> = value.into()?;

        Ok(Self {
            overhead_hashtable_main: values.remove_or_default("overhead.hashtable.main").into()?,
            overhead_hashtable_expires: values
                .remove_or_default("overhead.hashtable.expires")
                .into()?,
            overhead_hashtable_slot_to_keys: values
                .remove_or_default("overhead.hashtable.slot-to-keys")
                .into()?,
        })
    }
}

/// Options for the [`memory_usage`](crate::ServerCommands::memory_usage) command
#[derive(Default)]
pub struct MemoryUsageOptions {
    command_args: CommandArgs,
}

impl MemoryUsageOptions {
    /// For nested data types, the optional `samples` option can be provided,
    /// where count is the number of sampled nested values.
    /// By default, this option is set to 5.
    /// To sample the all of the nested values, use samples(0).
    #[must_use]
    pub fn samples(self, count: usize) -> Self {
        Self {
            command_args: self.command_args.arg("SAMPLES").arg(count),
        }
    }
}

impl IntoArgs for MemoryUsageOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}

/// Module information result for the [`module_list`](crate::ServerCommands::module_list) command.
pub struct ModuleInfo {
    /// Name of the module
    pub name: String,
    /// Version of the module
    pub version: String,
}

impl FromValue for ModuleInfo {
    fn from_value(value: Value) -> Result<Self> {
        let mut values: HashMap<String, Value> = value.into()?;

        Ok(Self {
            name: values.remove_or_default("name").into()?,
            version: values.remove_or_default("ver").into()?,
        })
    }
}

/// Options for the [`module_load`](crate::ServerCommands::module_load) command
#[derive(Default)]
pub struct ModuleLoadOptions {
    command_args: CommandArgs,
    args_added: bool,
}

impl ModuleLoadOptions {
    /// You can use this optional method to provide the module with configuration directives.
    /// This method can be called multiple times
    #[must_use]
    pub fn config<N, V>(self, name: N, value: V) -> Self
    where
        N: Into<BulkString>,
        V: Into<BulkString>,
    {
        if self.args_added {
            panic!("method config should be called before method arg");
        }

        Self {
            command_args: self.command_args.arg("CONFIG").arg(name).arg(value),
            args_added: false,
        }
    }

    /// Any additional arguments are passed unmodified to the module.
    /// This method can be called multiple times
    #[must_use]
    pub fn arg<A: Into<BulkString>>(self, arg: A) -> Self {
        if !self.args_added {
            Self {
                command_args: self.command_args.arg("ARGS").arg(arg),
                args_added: true,
            }
        } else {
            Self {
                command_args: self.command_args.arg(arg),
                args_added: false,
            }
        }
    }
}

impl IntoArgs for ModuleLoadOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}

/// options for the [`replicaof`](crate::ServerCommands::replicaof) command.
pub struct ReplicaOfOptions {
    command_args: CommandArgs,
}

impl ReplicaOfOptions {
    /// If a Redis server is already acting as replica,
    /// the command REPLICAOF NO ONE will turn off the replication,
    /// turning the Redis server into a MASTER.
    #[must_use]
    pub fn no_one() -> Self {
        Self {
            command_args: CommandArgs::Empty.arg("NO").arg("ONE"),
        }
    }

    /// In the proper form REPLICAOF hostname port will make the server
    /// a replica of another server listening at the specified hostname and port.
    #[must_use]
    pub fn master<H: Into<BulkString>>(host: H, port: u16) -> Self {
        Self {
            command_args: CommandArgs::Empty.arg(host).arg(port),
        }
    }
}

impl IntoArgs for ReplicaOfOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}

/// Result for the [`role`](crate::ServerCommands::role) command.
pub enum RoleResult {
    Master {
        /// The current master replication offset,
        /// which is an offset that masters and replicas share to understand,
        /// in partial resynchronizations,
        /// the part of the replication stream the replicas needs to fetch to continue.
        master_replication_offset: usize,
        /// information av=bout the connected replicas
        replica_infos: Vec<ReplicaInfo>,
    },
    Replica {
        /// The IP of the master.
        master_ip: String,
        /// The port number of the master.
        master_port: u16,
        /// The state of the replication from the point of view of the master
        state: ReplicationState,
        /// The amount of data received from the replica
        /// so far in terms of master replication offset.
        amount_data_received: isize,
    },
    Sentinel {
        /// An array of master names monitored by this Sentinel instance.
        master_names: Vec<String>,
    },
}

impl FromValue for RoleResult {
    fn from_value(value: Value) -> Result<Self> {
        let values: Vec<Value> = value.into()?;
        let mut iter = values.into_iter();

        match (
            iter.next(),
            iter.next(),
            iter.next(),
            iter.next(),
            iter.next(),
            iter.next(),
        ) {
            (
                Some(Value::BulkString(BulkString::Binary(s))),
                Some(master_replication_offset),
                Some(replica_infos),
                None,
                None,
                None,
            ) if s == b"master" => Ok(Self::Master {
                master_replication_offset: master_replication_offset.into()?,
                replica_infos: replica_infos.into()?,
            }),
            (
                Some(Value::BulkString(BulkString::Binary(s))),
                Some(master_ip),
                Some(master_port),
                Some(state),
                Some(amount_data_received),
                None,
            ) if s == b"slave" => Ok(Self::Replica {
                master_ip: master_ip.into()?,
                master_port: master_port.into()?,
                state: state.into()?,
                amount_data_received: amount_data_received.into()?,
            }),
            (
                Some(Value::BulkString(BulkString::Binary(s))),
                Some(master_names),
                None,
                None,
                None,
                None,
            ) if s == b"sentinel" => Ok(Self::Sentinel {
                master_names: master_names.into()?,
            }),
            _ => Err(Error::Client(
                "Cannot parse RoleResult from result".to_string(),
            )),
        }
    }
}

pub struct ReplicaInfo {
    /// the replica IP
    pub ip: String,
    /// the replica port
    pub port: u16,
    /// the last acknowledged replication offset.
    pub last_ack_offset: usize,
}

impl FromValue for ReplicaInfo {
    fn from_value(value: Value) -> Result<Self> {
        let (ip, port, last_ack_offset) = value.into()?;
        Ok(Self {
            ip,
            port,
            last_ack_offset,
        })
    }
}

pub enum ReplicationState {
    Connect,
    Connecting,
    Sync,
    Connected,
}

impl FromValue for ReplicationState {
    fn from_value(value: Value) -> Result<Self> {
        let str: String = value.into()?;

        match str.as_str() {
            "connect" => Ok(Self::Connect),
            "connecting" => Ok(Self::Connecting),
            "sync" => Ok(Self::Sync),
            "connected" => Ok(Self::Connected),
            _ => Err(Error::Client(format!(
                "Cannot parse {str} to ReplicationState"
            ))),
        }
    }
}

/// options for the [`shutdown`](crate::ServerCommands::shutdown) command.
#[derive(Default)]
pub struct ShutdownOptions {
    command_args: CommandArgs,
}

impl ShutdownOptions {
    /// - if save is true, will force a DB saving operation even if no save points are configured
    /// - if save is false, will prevent a DB saving operation even if one or more save points are configured.
    #[must_use]
    pub fn save(self, save: bool) -> Self {
        Self {
            command_args: self.command_args.arg(if save { "SAVE" } else { "NOSAVE" }),
        }
    }

    /// skips waiting for lagging replicas, i.e. it bypasses the first step in the shutdown sequence.
    #[must_use]
    pub fn now(self) -> Self {
        Self {
            command_args: self.command_args.arg("NOW"),
        }
    }

    /// ignores any errors that would normally prevent the server from exiting.
    #[must_use]
    pub fn force(self) -> Self {
        Self {
            command_args: self.command_args.arg("FORCE"),
        }
    }

    /// cancels an ongoing shutdown and cannot be combined with other flags.
    #[must_use]
    pub fn abort(self) -> Self {
        Self {
            command_args: self.command_args.arg("ABORT"),
        }
    }
}

impl IntoArgs for ShutdownOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}

/// options for the [`slowlog_get`](crate::ServerCommands::slowlog_get) command.
#[derive(Default)]
pub struct SlowLogOptions {
    command_args: CommandArgs,
}

impl SlowLogOptions {
    /// limits the number of returned entries, so the command returns at most up to `count` entries.
    #[must_use]
    pub fn count(self, count: usize) -> Self {
        Self {
            command_args: self.command_args.arg(count),
        }
    }
}

impl IntoArgs for SlowLogOptions {
    fn into_args(self, args: CommandArgs) -> CommandArgs {
        args.arg(self.command_args)
    }
}


/// Result [`slowlog_get`](crate::ServerCommands::slowlog_get) for the command.
pub struct SlowLogEntry {
    /// A unique progressive identifier for every slow log entry.
    pub id: i64,
    /// A unique progressive identifier for every slow log entry.
    pub unix_timestamp: u32,
    /// The amount of time needed for its execution, in microseconds.
    pub execution_time_micros: u64,
    /// The array composing the arguments of the command.
    pub command: Vec<String>,
    /// Client IP address and port.
    pub client_address: String,
    /// Client name if set via the CLIENT SETNAME command.
    pub client_name: String,
}

impl FromValue for SlowLogEntry {
    fn from_value(value: Value) -> Result<Self> {
        let (id, unix_timestamp, execution_time_micros, command, client_address, client_name) =
            value.into()?;

        Ok(Self {
            id,
            unix_timestamp,
            execution_time_micros,
            command,
            client_address,
            client_name,
        })
    }
}