use crate::db::Database;
use crate::identity::{IdKeyData, escape};
use std::path::Path;
use std::process::exit;

pub fn list_keys(
    db_path: &Path,
    local_only: bool,
    peer_only: bool,
    full_pks: bool,
) -> anyhow::Result<()> {
    if local_only && peer_only {
        eprintln!("cannot show only local and only peer keys, pick one");
        exit(1);
    }
    let show_local = !peer_only;
    let show_peer = !full_pks;

    let db = Database::load_or_create(db_path)?;

    let mut displayed = 0;

    for key in &db.keys {
        match key.keys {
            IdKeyData::Local(_) => {
                if !show_local {
                    continue;
                };
                displayed += 1;
                println!("local: {:?}", key);
            }
            IdKeyData::Peer(_) => {
                if !show_peer {
                    continue;
                };
                displayed += 1;
                println!("peer: {:?}", key);
            }
        }

        if full_pks {
            println!(
                "   pk: sage/{}/{}/{}",
                key.keys.pk()?,
                escape(key.name.clone()),
                escape(key.email.clone())
            );
        } else {
            println!("   id: {}", key.keys.keyid()?);
        }
    }

    if displayed == 0 {
        println!("no keys found");
    }

    Ok(())
}
