use crate::contacts_service::{error::ContactsServiceError, storage::database::Contact};
use tari_comms::types::CommsPublicKey;
use tari_service_framework::reply_channel::SenderService;
use tower::Service;
#[derive(Debug)]
pub enum ContactsServiceRequest {
GetContact(CommsPublicKey),
UpsertContact(Contact),
RemoveContact(CommsPublicKey),
GetContacts,
}
#[derive(Debug)]
pub enum ContactsServiceResponse {
ContactSaved,
ContactRemoved(Contact),
Contact(Contact),
Contacts(Vec<Contact>),
}
#[derive(Clone)]
pub struct ContactsServiceHandle {
handle: SenderService<ContactsServiceRequest, Result<ContactsServiceResponse, ContactsServiceError>>,
}
impl ContactsServiceHandle {
pub fn new(
handle: SenderService<ContactsServiceRequest, Result<ContactsServiceResponse, ContactsServiceError>>,
) -> Self {
Self { handle }
}
pub async fn get_contact(&mut self, pub_key: CommsPublicKey) -> Result<Contact, ContactsServiceError> {
match self.handle.call(ContactsServiceRequest::GetContact(pub_key)).await?? {
ContactsServiceResponse::Contact(c) => Ok(c),
_ => Err(ContactsServiceError::UnexpectedApiResponse),
}
}
pub async fn get_contacts(&mut self) -> Result<Vec<Contact>, ContactsServiceError> {
match self.handle.call(ContactsServiceRequest::GetContacts).await?? {
ContactsServiceResponse::Contacts(c) => Ok(c),
_ => Err(ContactsServiceError::UnexpectedApiResponse),
}
}
pub async fn upsert_contact(&mut self, contact: Contact) -> Result<(), ContactsServiceError> {
match self
.handle
.call(ContactsServiceRequest::UpsertContact(contact))
.await??
{
ContactsServiceResponse::ContactSaved => Ok(()),
_ => Err(ContactsServiceError::UnexpectedApiResponse),
}
}
pub async fn remove_contact(&mut self, pub_key: CommsPublicKey) -> Result<Contact, ContactsServiceError> {
match self
.handle
.call(ContactsServiceRequest::RemoveContact(pub_key))
.await??
{
ContactsServiceResponse::ContactRemoved(c) => Ok(c),
_ => Err(ContactsServiceError::UnexpectedApiResponse),
}
}
}