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
use crate::*;
use std::collections::{LinkedList, VecDeque};





/// Internal utility function
pub fn read_input_option_enumerated<T: Display + Clone>(choices: &[T], prompt: Option<String>, default: Option<usize>) -> BoxResult<(usize, T)> {
	if choices.is_empty() {return Err(Box::new(ListConstraintError::EmptyList));}
	
	let prompt = prompt.unwrap_or(String::from("Enter one of the following:"));
	let choice_strings =
		choices.iter()
		.map(ToString::to_string)
		.collect::<Vec<_>>();
	
	let print_prompt = || {
		println!("{prompt}");
		for (i, choice) in choice_strings.iter().enumerate() {
			if let Some(default) = default {
				if i == default {
					println!("[{choice}]");
				} else {
					println!(" {choice}");
				}
			} else {
				println!("{choice}");
			}
		}
		println!();
	};
	
	if choices.len() == 1 {
		print_prompt();
		println!();
		println!("Automatically choosing {} since it is the only option", choices[0]);
		return Ok((0, choices[0].clone()));
	}
	
	print_prompt();
	let mut input = read_stdin()?;
	
	loop {
		if input.is_empty() && let Some(default) = default {
			return Ok((default, choices[default].clone()));
		}
		
		// find exact match
		for (i, choice) in choice_strings.iter().enumerate() {
			if choice.eq_ignore_ascii_case(&input) {
				return Ok((i, choices[i].clone()));
			}
		}
		
		println!();
		println!("Invalid option.");
		
		// try fuzzy match
		let possible_choice_index = custom_fuzzy_search(&input, &choice_strings);
		print!("Did you mean \"{}\"? (enter nothing to confirm, or re-enter input) ", choice_strings[possible_choice_index]);
		let new_input = read_stdin()?;
		if new_input.is_empty() {
			return Ok((possible_choice_index, choices[possible_choice_index].clone()));
		}
		input = new_input;
		
	}
}

/// Internal utility function
pub fn read_input_option<T: Display + Clone>(choices: &[T], prompt: Option<String>, default: Option<usize>) -> BoxResult<T> {
	read_input_option_enumerated(choices, prompt, default).map(|(_index, output)| output)
}

/// Error type
#[derive(Debug)]
pub enum ListConstraintError {
	/// This exists because an empty list would be a softlock
	EmptyList,
}

impl Error for ListConstraintError {}

impl Display for ListConstraintError {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		match self {
			Self::EmptyList => write!(f, "List Constraint is empty"),
		}
	}
}



/// Custom implementation of fuzzy search, returns the index of the closest match
pub fn custom_fuzzy_search(pattern: &str, items: &[String]) -> usize {
	let (mut best_score, mut best_index) = (custom_fuzzy_match(pattern, &items[0]), 0);
	for (i, item) in items.iter().enumerate().skip(1) {
		let score = custom_fuzzy_match(pattern, item);
		if score > best_score {
			best_score = score;
			best_index = i;
		}
	}
	best_index
}

/// Custom implementation of fuzzy match. Not efficient at all, but gives good results
pub fn custom_fuzzy_match(pattern: &str, item: &str) -> usize {
	let mut best_score = 0;
	let offset_start = pattern.len() as isize * -1 + 1;
	let offset_end = item.len() as isize - 1;
	for offset in offset_start..=offset_end {
		let item_slice = &item[offset.max(0) as usize .. (offset + pattern.len() as isize).min(item.len() as isize) as usize];
		let pattern_slice = &pattern[(offset * -1).max(0) as usize .. (item.len() as isize - offset).min(pattern.len() as isize) as usize];
		let mut slice_score = 0;
		for (item_char, pattern_char) in item_slice.chars().zip(pattern_slice.chars()) {
			if item_char.eq_ignore_ascii_case(&pattern_char) {
				slice_score += 3;
			} else {
				slice_score -= 1;
			}
		}
		best_score = (best_score as isize).max(slice_score) as usize;
	}
	best_score
}





/// Allows you to add more data to an option
/// 
/// Example:
/// 
/// ```
/// // example data
/// let mut colors = vec!("Red", "green", "Blue");
/// 
/// // prepare options, only capitalized colors can be removed
/// let choosable_colors =
/// 	colors.iter().enumerate()
/// 	.filter_map(|(i, color_name)| {
/// 		let first_char = color_name.chars().next()?;
/// 		if first_char.is_lowercase() {return None;}
/// 		Some(OptionWithData {name: color_name.to_string(), data: i})
/// 	})
/// 	.collect::<Vec<_>>();
/// 
/// // prompt
/// let OptionWithData {name: _, data: index_to_remove} = prompt!("Choose a color to remove: "; choosable_colors);
/// colors.remove(index_to_remove);
/// ```
#[derive(Clone, PartialEq)]
pub struct OptionWithData<T: Clone + PartialEq> {
	/// What's shown to the user
	pub display_name: String,
	/// What isn't shown to the user
	pub data: T,
}

impl<T: Clone + PartialEq> Display for OptionWithData<T> {
	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
		write!(f, "{}", self.display_name)
	}
}





impl<T: Display + Clone + PartialEq> TryRead for &[T] {
	type Output = T;
	fn try_read_line(&self, prompt: Option<String>, default: Option<Self::Output>) -> BoxResult<Self::Output> {
		let default =
			self.iter().enumerate()
			.find(|v| Some(v.1) == default.as_ref())
			.map(|v| v.0);
		read_input_option(self, prompt, default)
	}
}

impl<T: Display + Clone + PartialEq, const LEN: usize> TryRead for &[T; LEN] {
	type Output = T;
	fn try_read_line(&self, prompt: Option<String>, default: Option<Self::Output>) -> BoxResult<Self::Output> {
		let default =
			self.iter().enumerate()
			.find(|v| Some(v.1) == default.as_ref())
			.map(|v| v.0);
		#[allow(clippy::explicit_auto_deref)] // false positive
		read_input_option(*self, prompt, default)
	}
}

impl<T: Display + Clone + PartialEq> TryRead for Vec<T> {
	type Output = T;
	fn try_read_line(&self, prompt: Option<String>, default: Option<Self::Output>) -> BoxResult<Self::Output> {
		let default =
			self.iter().enumerate()
			.find(|v| Some(v.1) == default.as_ref())
			.map(|v| v.0);
		read_input_option(self, prompt, default)
	}
}

impl<T: Display + Clone + PartialEq> TryRead for VecDeque<T> {
	type Output = T;
	fn try_read_line(&self, prompt: Option<String>, default: Option<Self::Output>) -> BoxResult<Self::Output> {
		let default =
			self.iter().enumerate()
			.find(|v| Some(v.1) == default.as_ref())
			.map(|v| v.0);
		read_input_option(&self.iter().cloned().collect::<Vec<_>>(), prompt, default)
	}
}

impl<T: Display + Clone + PartialEq> TryRead for LinkedList<T> {
	type Output = T;
	fn try_read_line(&self, prompt: Option<String>, default: Option<Self::Output>) -> BoxResult<Self::Output> {
		let default =
			self.iter().enumerate()
			.find(|v| Some(v.1) == default.as_ref())
			.map(|v| v.0);
		read_input_option(&self.iter().cloned().collect::<Vec<_>>(), prompt, default)
	}
}



/// Returns the index of the chosen item along with the item. &nbsp; <b> NOTE </b> : If you filter the inputs before feeding them into EnumerateInput, the indices returns won't match the indices of the initial input. In this case, you might want to use OptionWithData instead
pub struct EnumerateInput<T: TryRead> (pub T);

impl<T: Display + Clone + PartialEq> TryRead for EnumerateInput<&[T]> {
	type Output = (usize, T);
	fn try_read_line(&self, prompt: Option<String>, default: Option<Self::Output>) -> BoxResult<Self::Output> {
		let default_index = if let Some((index, _item)) = &default {
			Some(*index)
		} else {
			None
		};
		read_input_option_enumerated(self.0, prompt, default_index)
	}
}

impl<T: Display + Clone + PartialEq, const LEN: usize> TryRead for EnumerateInput<&[T; LEN]> {
	type Output = (usize, T);
	fn try_read_line(&self, prompt: Option<String>, default: Option<Self::Output>) -> BoxResult<Self::Output> {
		let default_index = if let Some((index, _item)) = &default {
			Some(*index)
		} else {
			None
		};
		read_input_option_enumerated(self.0, prompt, default_index)
	}
}

impl<T: Display + Clone + PartialEq> TryRead for EnumerateInput<Vec<T>> {
	type Output = (usize, T);
	fn try_read_line(&self, prompt: Option<String>, default: Option<Self::Output>) -> BoxResult<Self::Output> {
		let default_index = if let Some((index, _item)) = &default {
			Some(*index)
		} else {
			None
		};
		read_input_option_enumerated(&self.0, prompt, default_index)
	}
}

impl<T: Display + Clone + PartialEq> TryRead for EnumerateInput<VecDeque<T>> {
	type Output = (usize, T);
	fn try_read_line(&self, prompt: Option<String>, default: Option<Self::Output>) -> BoxResult<Self::Output> {
		let default_index = if let Some((index, _item)) = &default {
			Some(*index)
		} else {
			None
		};
		let slice = self.0.iter().cloned().collect::<Vec<_>>();
		read_input_option_enumerated(&slice, prompt, default_index)
	}
}

impl<T: Display + Clone + PartialEq> TryRead for EnumerateInput<LinkedList<T>> {
	type Output = (usize, T);
	fn try_read_line(&self, prompt: Option<String>, default: Option<Self::Output>) -> BoxResult<Self::Output> {
		let default_index = if let Some((index, _item)) = &default {
			Some(*index)
		} else {
			None
		};
		let slice = self.0.iter().cloned().collect::<Vec<_>>();
		read_input_option_enumerated(&slice, prompt, default_index)
	}
}