use crate::AccountId;
use crate::Error;
use serde::{Deserialize, Serialize};
use std::{fmt, str::FromStr};
#[typeshare::typeshare]
#[derive(Debug, Clone, Serialize, Deserialize, Eq, PartialEq, Hash)]
pub struct PublicIdentity {
account_id: AccountId,
label: String,
}
impl PublicIdentity {
pub fn new(account_id: AccountId, label: String) -> Self {
Self { account_id, label }
}
pub fn account_id(&self) -> &AccountId {
&self.account_id
}
pub fn label(&self) -> &str {
&self.label
}
pub fn set_label(&mut self, label: String) {
self.label = label;
}
}
impl From<&PublicIdentity> for AccountRef {
fn from(value: &PublicIdentity) -> Self {
AccountRef::Id(*value.account_id())
}
}
impl From<PublicIdentity> for AccountRef {
fn from(value: PublicIdentity) -> Self {
(&value).into()
}
}
#[derive(Debug, Clone)]
pub enum AccountRef {
Id(AccountId),
Name(String),
}
impl fmt::Display for AccountRef {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Id(id) => write!(f, "{}", id),
Self::Name(name) => write!(f, "{}", name),
}
}
}
impl FromStr for AccountRef {
type Err = Error;
fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
if let Ok(id) = s.parse::<AccountId>() {
Ok(Self::Id(id))
} else {
Ok(Self::Name(s.to_string()))
}
}
}