summaryrefslogblamecommitdiff
path: root/src/input.rs
blob: 689389ebe3df01dfc486f4363b2726da857aaf73 (plain) (tree)


























































                                                                                                                                           
use std::io::{stdin, Error, ErrorKind};
use crate::{add, config::Cfg};

pub struct Input {
    pub command: String,
    pub args: Option<Vec<String>>,
}

impl Input {
    pub fn from(string: String) -> Result<Self, Box<dyn std::error::Error>> {
        let mut split: Vec<&str> = string.split(' ').collect();

        let command: String;
        let mut args: Option<Vec<String>> = None;

        if split[0].is_empty() { split.remove(0); };

        dbg!(&split);

        match split.len() {
            0 => { Err(Box::new(Error::new(ErrorKind::InvalidInput, "NO_ARGS"))) } 
            1 => Ok( Input { command: split[0].to_string(), args }),
            2.. => {
                command = split[0].to_string();
                split.remove(0);
                let mut str_args: Vec<String> = vec![];
                for e in split {
                    str_args.push(e.to_string());
                }
                args = Some(str_args);
                Ok(Input { command, args })
            },
            _ => { panic!("This should never happen") } 
        }


    }
}

pub async fn get_input(config: Cfg) -> Result<(), Box<dyn std::error::Error>> {
    let mut user_input = String::new();
    stdin()
        .read_line(&mut user_input)
        .expect("ERROR");

    dbg!(&user_input);

    let input = Input::from(user_input.trim().to_string())?;

    match input.command.as_str() {
        "add" => { 
            if input.args == None { return Err(Box::new(Error::new(ErrorKind::InvalidInput, "TOO_FEW_ARGUMENTS"))) };
            if input.args.as_ref().unwrap().len() != 1 { return Err(Box::new(Error::new(ErrorKind::InvalidInput, "TOO_MANY_ARGUMENTS"))) };
            add(config, input.args.unwrap()[0].to_string()).await?;
            Ok(()) 
        },
        _ => Err(Box::new(Error::new(ErrorKind::InvalidInput, "UNKNOWN_COMMAND"))),
    }
}