use anyhow::bail;
use serde::{Deserialize, Serialize};
use std::fmt::{Debug, Formatter};
use std::str::FromStr;

#[derive(Serialize, Deserialize, Clone)]
pub struct Identity {
    pub name: String,
    pub email: String,
    pub keys: IdKeyData,
}
#[derive(Serialize, Deserialize, Clone)]
pub enum IdKeyData {
    Local(String),
    Peer(String),
}

impl Debug for Identity {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{} <{}>", self.name, self.email)
    }
}
impl IdKeyData {
    pub fn pk(&self) -> anyhow::Result<String> {
        match self {
            IdKeyData::Local(id) => {
                let k = match age::x25519::Identity::from_str(id) {
                    Ok(k) => k,
                    Err(e) => {
                        bail!(e);
                    }
                };
                Ok(k.to_public().to_string())
            }
            IdKeyData::Peer(pk) => Ok(pk.clone()),
        }
    }
    pub fn keyid(&self) -> anyhow::Result<String> {
        let pk = self.pk()?;
        let s0 = &pk[4..12];
        Ok(s0.to_string())
    }
}

pub fn escape(i: String) -> String {
    urlencoding::encode(&i).to_string()
}
pub fn unescape(i: String) -> anyhow::Result<String> {
    Ok(urlencoding::decode(&i)?.to_string())
}
