-
Notifications
You must be signed in to change notification settings - Fork 86
/
Copy pathConsoleSwitch.cs
310 lines (250 loc) · 9.62 KB
/
ConsoleSwitch.cs
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
using System.ComponentModel;
namespace Signum.Utilities;
public class ConsoleSwitch<K, V> : IEnumerable<KeyValuePair<string, WithDescription<V>>>
where K : notnull
where V : class
{
readonly Dictionary<string, WithDescription<V>> dictionary = new Dictionary<string, WithDescription<V>>(StringComparer.InvariantCultureIgnoreCase);
readonly Dictionary<int, string> separators = new Dictionary<int, string>();
readonly string welcomeMessage;
public ConsoleSwitch()
: this(ConsoleMessage.SelectOneOfTheFollowingOptions.NiceToString())
{
}
public ConsoleSwitch(string welcomeMessage)
{
this.welcomeMessage = welcomeMessage;
}
//Separator
public void Add(string value)
{
separators.AddOrThrow(dictionary.Keys.Count, value, "Already a separator on {0}");
}
public void Add(K key, V value)
{
dictionary.AddOrThrow(key.ToString()!, new WithDescription<V>(value), "Key {0} already in ConsoleSwitch");
}
public void Add(K key, V value, string description)
{
dictionary.AddOrThrow(key.ToString()!, new WithDescription<V>(value, description), "Key {0} already in ConsoleSwitch");
}
public V? Choose(int? numberOfOptions = null)
{
var tuple = ChooseTuple(numberOfOptions);
if (tuple == null)
return null;
return tuple.Value;
}
public WithDescription<V>? ChooseTuple(int? numberOfOptions = null)
{
Console.WriteLine(welcomeMessage);
var noOfOptsPerScreen = numberOfOptions ?? dictionary.Count;
PrintOptions(0, noOfOptsPerScreen);
var noOfOptsPrinted = noOfOptsPerScreen;
do
{
var input = Console.ReadLine()?.Trim();
if (input == "+")
{
if (noOfOptsPrinted >= dictionary.Count)
continue;
PrintOptions(noOfOptsPrinted, noOfOptsPerScreen);
}
else
{
if (string.IsNullOrWhiteSpace(input))
return null;
var val = TryGetValue(input);
if (val != null)
return val;
SafeConsole.WriteLineColor(ConsoleColor.Red, "Plase choose a valid option!");
noOfOptsPrinted = 0;
PrintOptions(noOfOptsPrinted, noOfOptsPerScreen);
}
noOfOptsPrinted += noOfOptsPerScreen;
} while (true);
}
void PrintOptions(int skip, int take)
{
var keys = dictionary.Keys.ToList();
var max = Math.Min(keys.Count, skip + take);
for (int i = skip; i < max; i++)
{
var key = keys[i];
string? value = separators.TryGetC(i);
if (value.HasText())
{
Console.WriteLine();
Console.WriteLine(value);
}
PrintOption(key, dictionary[key]);
}
if (skip + take >= dictionary.Count) return;
SafeConsole.WriteColor(ConsoleColor.White, " +");
Console.WriteLine(" - " + ConsoleMessage.More.NiceToString());
}
public Action<string, WithDescription<V>> PrintOption = (key, vwd) =>
{
SafeConsole.WriteColor(ConsoleColor.White, " " + key);
Console.WriteLine(" - " + vwd.Description);
};
public V[]? ChooseMultiple(string[]? args = null)
{
return ChooseMultiple(ConsoleMessage.EnterYoutSelectionsSeparatedByComma.NiceToString(), args);
}
public V[]? ChooseMultiple(string endMessage, string[]? args = null)
{
var array = ChooseMultipleWithDescription(endMessage, args);
if (array == null)
return null;
return array.Select(a => a.Value).ToArray();
}
public WithDescription<V>[]? ChooseMultipleWithDescription(string[]? args = null)
{
return ChooseMultipleWithDescription(ConsoleMessage.EnterYoutSelectionsSeparatedByComma.NiceToString(), args);
}
public WithDescription<V>[]? ChooseMultipleWithDescription(string endMessage, string[]? args = null)
{
if (args != null)
return args.ToString(" ").SplitNoEmpty(',').SelectMany(GetValuesRange).ToArray();
retry:
try
{
Console.WriteLine(welcomeMessage);
PrintOptions(0, this.dictionary.Count);
Console.WriteLine(endMessage);
string? line = Console.ReadLine();
if (string.IsNullOrEmpty(line))
{
Console.Clear();
return null;
}
Console.WriteLine();
return line.SplitNoEmpty(',').SelectMany(GetValuesRange).ToArray();
}
catch (Exception e)
{
Console.WriteLine(e.Message);
goto retry;
}
}
IEnumerable<WithDescription<V>> GetValuesRange(string line)
{
if (line.Contains('-'))
{
int? from = line.Before('-')?.Let(s => s.HasText() ? GetIndex(s.Trim()) : (int?)null);
int? to = line.After('-')?.Let(s => s.HasText() ? GetIndex(s.Trim()) : (int?)null);
if (from == null && to == null)
return Enumerable.Empty<WithDescription<V>>();
if (from == null && to != null)
return dictionary.Keys.Take(to.Value + 1).Select(s => dictionary.GetOrThrow(s));
if (from != null && to == null)
return dictionary.Keys.Skip(from.Value).Select(s => dictionary.GetOrThrow(s));
return dictionary.Keys.Skip(from!.Value).Take((to!.Value + 1) - from.Value).Select(s => dictionary.GetOrThrow(s));
}
else
{
return new[] { GetValue(line.Trim()) };
}
}
int GetIndex(string value)
{
int index = dictionary.Keys.IndexOf(value);
if (index == -1)
throw new KeyNotFoundException(ConsoleMessage.NoOptionWithKey0Found.NiceToString().FormatWith(value));
return index;
}
WithDescription<V>? TryGetValue(string input)
{
var exact = dictionary.TryGetC(input);
if (exact != null)
return exact;
var sd = new StringDistance();
var best = dictionary.Keys.MinBy(a => sd.LevenshteinDistance(input.ToLowerInvariant(), a.ToLowerInvariant()));
if (best != null && sd.LevenshteinDistance(input.ToLowerInvariant(), best.ToLowerInvariant()) <= 2)
{
if (SafeConsole.Ask($"Did you mean '{best}'?"))
return dictionary.GetOrThrow(best);
}
return null;
}
WithDescription<V> GetValue(string input)
{
var result = TryGetValue(input);
if (result == null)
throw new KeyNotFoundException(ConsoleMessage.NoOptionWithKey0Found.NiceToString(input));
return result;
}
public IEnumerator<KeyValuePair<string, WithDescription<V>>> GetEnumerator()
{
return dictionary.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public enum ConsoleMessage
{
[Description("Enter your selection (nothing to exit): ")]
EnterYourSelection,
[Description("Enter your selections separated by comma or hyphen (nothing to exit): ")]
EnterYoutSelectionsSeparatedByComma,
[Description("No option with key {0} found")]
NoOptionWithKey0Found,
[Description("Select one of the following options:")]
SelectOneOfTheFollowingOptions,
[Description("more...")]
More
}
public class WithDescription<T>
where T : class
{
public T Value { get; private set; }
public string Description { get; private set; }
public WithDescription(T value)
: this(value, DefaultDescription(value))
{
}
public WithDescription(T value, string description)
{
this.Value = value;
this.Description = description;
}
static string DefaultDescription(object value)
{
if (value is Delegate d)
return d.Method.Name.SpacePascal(true);
if (value is Enum e)
return e.NiceToString();
if (value == null)
return "[No Name]";
return value.ToString()!;
}
}
public static class ConsoleSwitchExtensions
{
public static T? ChooseConsole<T>(this IEnumerable<T> collection, Func<T, string>? getString = null, string? message = null) where T : class {
var cs = new ConsoleSwitch<int, T>(message ?? ConsoleMessage.SelectOneOfTheFollowingOptions.NiceToString());
cs.Load(collection.ToList(), getString);
return cs.Choose();
}
public static T[]? ChooseConsoleMultiple<T>(this IEnumerable<T> collection, Func<T, string>? getString = null, string? message = null) where T : class
{
var cs = new ConsoleSwitch<int, T>(message ?? ConsoleMessage.SelectOneOfTheFollowingOptions.NiceToString());
cs.Load(collection.ToList(), getString);
return cs.ChooseMultiple();
}
public static ConsoleSwitch<int, T> Load<T>(this ConsoleSwitch<int, T> cs, List<T> collection, Func<T, string>? getString = null) where T : class
{
for (int i = 0; i < collection.Count; i++)
{
var item = collection[i];
if (getString != null)
cs.Add(i, item, getString(item));
else
cs.Add(i, item);
}
return cs;
}
}