use dialoguer::{Input, theme::ColorfulTheme};
use keyring::Entry;

pub fn get_token<'a>(service: &str, username: &str) -> String {
    let entry = Entry::new(service, username).expect("Failed to get keyring entry");
    match entry.get_password() {
        Ok(token) => token,
        Err(_) => {
            let token: String = Input::with_theme(&ColorfulTheme::default())
                .with_prompt("Enter your bot token")
                .interact_text()
                .unwrap();
            match entry.set_password(&token) {
                Ok(_) => {}
                Err(e) => {
                    println!("Failed to set token: {}", e);
                    std::process::abort()
                }
            };
            token
        }
    }
}

pub fn change_token(service: &str, username: &str) {
    let entry = Entry::new(service, username).expect("Failed to get keyring entry");
    let new_token: String = Input::with_theme(&ColorfulTheme::default())
        .with_prompt("New Token")
        .interact_text()
        .unwrap();
    let _ = entry.set_password(&new_token);
}

pub fn remove_token(service: &str, username: &str) {
    let entry = Entry::new(service, username).expect("Failed to get keyring entry");
    let _ = entry.delete_credential();
}
