task_manager/
user_input.rs

1use crate::{
2    display_message, Color, ALTERNATIVE_DATETIME_FORMAT, DATETIME_FORMAT, DATE_FORMAT, TIME_FORMAT,
3};
4use chrono::{TimeZone, Utc};
5use dialoguer::{theme::ColorfulTheme, Confirm, Input, Select};
6use std::fmt::Display;
7
8///Get boolean response
9pub fn get_user_confirmation(question: &str) -> bool {
10    Confirm::with_theme(&ColorfulTheme::default())
11        .with_prompt(question)
12        .default(true)
13        .interact()
14        .unwrap()
15}
16
17///Get text response.
18pub fn get_user_input(text: &str, default_text: &str, allow_spaces: bool) -> Option<String> {
19    let res: String = Input::with_theme(&ColorfulTheme::default())
20        .with_prompt(text)
21        .default(default_text.into())
22        .interact_text()
23        .unwrap();
24
25    if allow_spaces {
26        return Some(res);
27    }
28
29    let text_parts = &res.split_ascii_whitespace().count();
30    if text_parts != &1_usize {
31        display_message("error", "Spaces are not allowed", crate::Color::Red);
32        return None;
33    }
34    let res = res.split_ascii_whitespace().next().unwrap().to_string();
35    Some(res)
36}
37
38//Get singe response from choices
39pub fn get_user_selection<T>(items: &Vec<T>, title: &str) -> (String, usize)
40where
41    T: Display,
42{
43    let selection = Select::with_theme(&ColorfulTheme::default())
44        .items(&items)
45        .with_prompt(title)
46        .default(0)
47        .interact()
48        .unwrap();
49
50    (items.get(selection).unwrap().to_string(), selection)
51}
52
53//Get date response
54pub fn get_user_date(midnight: bool, must_be_future: bool) -> Option<String> {
55    let now = Utc::now();
56    let today_str = now.format(DATE_FORMAT).to_string();
57    let midnight_time = "00:00:00";
58
59    let current_time_str = match midnight {
60        true => midnight_time.to_string(),
61        false => now.format(TIME_FORMAT).to_string(),
62    };
63
64    let datetime_str = format!(
65        "{} {}",
66        get_user_input(
67            format!("Date ({})", DATE_FORMAT).as_str(),
68            &today_str,
69            false
70        )
71        .unwrap(),
72        current_time_str
73    );
74    let datetime_date = Utc.datetime_from_str(&datetime_str, &ALTERNATIVE_DATETIME_FORMAT);
75
76    if datetime_date.is_err() {
77        display_message("error", "Invalid date", Color::Red);
78        return None;
79    }
80
81    if must_be_future {
82        if now > datetime_date.unwrap() {
83            display_message("error", "Datetime cannot be past", Color::Red);
84            return None;
85        }
86    }
87    let datetime_str = datetime_date.unwrap().format(DATETIME_FORMAT).to_string();
88    Some(datetime_str)
89}